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

import unittest
import tempfile
import shutil

import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from DebianDevelChangesBot.datasources import AptArchive

class TestDatasourceAptArchive(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        # FIXME make sure we do not have to fetch
        apt_config = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                               '..', 'bot-config', 'apt')
        cls.statedir = tempfile.mkdtemp()

        cls.apt_archive = AptArchive(apt_config, cls.statedir)
        cls.apt_archive.update_index(True)
        cls.apt_archive.update()

    @classmethod
    def tearDownClass(cls):
        shutil.rmtree(cls.statedir, True)

    def testVLC(self):
        info = self.apt_archive.get_maintainer('vlc')
        self.assertEqual(info['email'], 'pkg-multimedia-maintainers@lists.alioth.debian.org')
        self.assertEqual(info['name'], 'Debian Multimedia Maintainers')

    def testSourceVLC(self):
        info = self.apt_archive.get_maintainer('src:vlc')
        self.assertEqual(info['email'], 'pkg-multimedia-maintainers@lists.alioth.debian.org')
        self.assertEqual(info['name'], 'Debian Multimedia Maintainers')

    def testUdev(self):
        info = self.apt_archive.get_maintainer('udev')
        self.assertEqual(info['email'], 'pkg-systemd-maintainers@lists.alioth.debian.org')
        self.assertEqual(info['name'], 'Debian systemd Maintainers')

    def testPseudoPackage(self):
        info = self.apt_archive.get_maintainer('wnpp')
        self.assertEqual(info['email'], 'wnpp@debian.org')

if __name__ == "__main__":
    unittest.main()
<commit_msg>Fix vlc based tests<commit_after>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#   Debian Changes Bot
#   Copyright (C) 2016 Sebastian Ramacher <sramacher@debian.org>
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU Affero General Public License as
#   published by the Free Software Foundation, either version 3 of the
#   License, or (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU Affero General Public License for more details.
#
#   You should have received a copy of the GNU Affero General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.

import unittest
import tempfile
import shutil

import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from DebianDevelChangesBot.datasources import AptArchive

class TestDatasourceAptArchive(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        # FIXME make sure we do not have to fetch
        apt_config = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                               '..', 'bot-config', 'apt')
        cls.statedir = tempfile.mkdtemp()

        cls.apt_archive = AptArchive(apt_config, cls.statedir)
        cls.apt_archive.update_index(True)
        cls.apt_archive.update()

    @classmethod
    def tearDownClass(cls):
        shutil.rmtree(cls.statedir, True)

    def testVLC(self):
        info = self.apt_archive.get_maintainer('vlc')
        self.assertEqual(info['email'], 'debian-multimedia@lists.debian.org')
        self.assertEqual(info['name'], 'Debian Multimedia Maintainers')

    def testSourceVLC(self):
        info = self.apt_archive.get_maintainer('src:vlc')
        self.assertEqual(info['email'], 'debian-multimedia@lists.debian.org')
        self.assertEqual(info['name'], 'Debian Multimedia Maintainers')

    def testUdev(self):
        info = self.apt_archive.get_maintainer('udev')
        self.assertEqual(info['email'], 'pkg-systemd-maintainers@lists.alioth.debian.org')
        self.assertEqual(info['name'], 'Debian systemd Maintainers')

    def testPseudoPackage(self):
        info = self.apt_archive.get_maintainer('wnpp')
        self.assertEqual(info['email'], 'wnpp@debian.org')

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


<commit_before># -*- encoding: UTF-8 -*-
from __future__ import absolute_import, unicode_literals

import six

from bson.objectid import ObjectId
from mock import patch

from mongorest.collection import Collection
from mongorest.document import Document
from mongorest.testcase import TestCase

__all__ = [
    'TestDocument',
]

class TestDocument(TestCase):

    # __init__
    def test_init_sets_correct_collection_if_inherits_from_collection(self):
        document = Document(Collection)

        self.assertEqual(document._collection, Collection)

    def test_init_raises_error_if_collection_does_not_inherit_from_collection(self):
        with self.assertRaises(AttributeError):
            Document(Document)

    def test_init_sets_correct_fields(self):
        document = Document(Collection, {'test': 'test'})

        self.assertEqual(document._fields, {'test': 'test'})

    @patch('mongorest.document.Document._validate')
    def test_init_calls_validate(self, validate):
        Document(Collection)

        self.assertEqual(validate.call_count, 1)

    @patch('mongorest.document.Document._process')
    def test_init_calls_process_if_not_processed(self, process):
        Document(Collection, processed=False)

        self.assertEqual(process.call_count, 1)

    @patch('mongorest.document.Document._process')
    def test_init_does_not_call_process_if_processed(self, process):
        Document(Collection, processed=True)

        self.assertEqual(process.call_count, 0)

    # __getattr__ is not being formally tested.
    # Its usage on the other tested functions will make sure it works.

    def test_set_attr_correctly_sets__errors(self):
        document = Document(Collection)
        document._errors = {'test': 'test'}

        self.assertEqual(document._errors, {'test': 'test'})

    def test_set_attr_correctly_sets__fields(self):
        document = Document(Collection)
        document._fields = {'test': 'test'}

        self.assertEqual(document._fields, {'test': 'test'})

    def test_set_attr_correctly_sets__collection(self):
        document = Document(Collection)

        class TestCollection(Collection):
            pass

        document._collection = TestCollection

        self.assertEqual(document._collection, TestCollection)

    def test_set_attr_correctly_sets_field(self):
        document = Document(Collection)
        document.test = 1

        self.assertEqual(document._fields['test'], 1)

    def test_repr_returns_correct_representation_of_the_document(self):
        document = Document(Collection)

        self.assertEqual(
            document.__repr__(),
            '<Document<Collection> object at {0}>'.format(hex(id(document)))
        )

    # _validate
    def test_validate_sets_error_if_required_field_is_not_present_on_document(self):
        class TestCollection(Collection):
            meta = {
                'required': {'test': six.string_types + six.integer_types},
                'optional': {}
            }

        document = Document(TestCollection)

        self.assertEqual(
            document.errors,
            {
                'error_code': 1,
                'error_type': 'ValidationError',
                'error_message': 'TestCollection document validation failed.',
                'errors': [
                    {
                        'error_code': 2,
                        'error_type': 'RequiredFieldError',
                        'error_message': 'Field \'test\' is required.',
                        'collection': 'TestCollection',
                        'field': 'test',
                    },
                ],
                'collection': 'TestCollection',
                'document': {},
            }
        )

    def test_validate_sets_error_if_required_field_has_wrong_type(self):
        class TestCollection(Collection):
            meta = {
                'required': {'test': ObjectId},
                'optional': {}
            }

        document = Document(TestCollection, {'test': 1.1})

        self.assertEqual(
            document.errors,
            {
                'error_code': 1,
                'error_type': 'ValidationError',
                'error_message': 'TestCollection document validation failed.',
                'errors': [
                    {
                        'error_code': 3,
                        'error_type': 'FieldTypeError',
                        'error_message': 'Field \'test\' must be of type(s): ObjectId.',
                        'collection': 'TestCollection',
                        'field': 'test',
                        'types': 'ObjectId',
                    },
                ],
                'collection': 'TestCollection',
                'document': {'test': 1.1},
            }
        )

    def test_validate_sets_error_if_optional_field_has_wrong_type(self):
        class TestCollection(Collection):
            meta = {
                'required': {},
                'optional': {'test': ObjectId}
            }

        document = Document(TestCollection, {'test': 1.1})

        self.assertEqual(
            document.errors,
            {
                'error_code': 1,
                'error_type': 'ValidationError',
                'error_message': 'TestCollection document validation failed.',
                'errors': [
                    {
                        'error_code': 3,
                        'error_type': 'FieldTypeError',
                        'error_message': 'Field \'test\' must be of type(s): ObjectId.',
                        'collection': 'TestCollection',
                        'field': 'test',
                        'types': 'ObjectId',
                    },
                ],
                'collection': 'TestCollection',
                'document': {'test': 1.1},
            }
        )

    # _process
    def test_process_calls_collections_process_functions(self):
        class TestCollection(Collection):
            def process1(self):
                pass

        with patch.object(TestCollection, 'process1') as process1:
            Document(TestCollection)

            self.assertEqual(process1.call_count, 1)

    # is_valid
    def test_is_valid_returns_true_if_no_errors(self):
        document = Document(Collection)
        document._errors = {}

        self.assertTrue(Document(Collection).is_valid)

    def test_is_valid_returns_false_if_there_are_errors(self):
        document = Document(Collection)
        document._errors = {'test': 'test'}

        self.assertFalse(document.is_valid)

    # fields
    def test_fields_returns_empty_dict_if_no_fields(self):
        document = Document(Collection, {})

        self.assertEqual({}, document.fields)

    def test_fields_returns_documents_fields(self):
        document = Document(Collection, {'test': ObjectId()})

        self.assertEqual(document._fields, document.fields)

    # errors
    def test_errors_returns_empty_dict_if_no_errors(self):
        document = Document(Collection, {})
        document._errors = {}

        self.assertEqual({}, document.errors)

    def test_errors_returns_documents_errors(self):
        class TestCollection(Collection):
            meta = {
                'required': {'test': six.string_types + six.integer_types},
                'optional': {}
            }

        document = Document(TestCollection, {'test': ObjectId()})

        self.assertEqual(document._errors, document.errors)

    # save
    def test_save_is_decorated_with_serializable(self):
        self.assertIn('serializable', Document.save.decorators)

    def test_save_returns_errors_if_document_is_not_valid(self):
        class TestCollection(Collection):
            meta = {
                'required': {'test': ObjectId},
                'optional': {}
            }

        errors = Document(TestCollection).save()

        self.assertEqual(
            errors,
            {
                'error_code': 1,
                'error_type': 'ValidationError',
                'error_message': 'TestCollection document validation failed.',
                'errors': [
                    {
                        'error_code': 2,
                        'error_type': 'RequiredFieldError',
                        'error_message': 'Field \'test\' is required.',
                        'collection': 'TestCollection',
                        'field': 'test',
                    },
                ],
                'collection': 'TestCollection',
                'document': {},
            }
        )

    def test_save_returns_errors_if_error_ocurred_during_save(self):
        Collection.collection.create_index('test', unique=True)
        Collection.insert_one({'test': 'test'})

        document = Document(Collection)
        document.test = 'test'
        errors = document.save()

        self.assertEqual(errors['error_code'], 0)
        self.assertEqual(errors['error_type'], 'PyMongoError')

        Collection.drop_index('test_1')

    def test_save_returns_error_if_restricted_unique(self):
        class TestCollection(Collection):

            @classmethod
            def restrict_unique(cls, document):
                return {
                    'error_code': 7, 'error_type': 'NotUnique',
                    'error_message': 'Document is not unique.',
                }

        errors = Document(TestCollection).save()
        self.assertEqual(
            errors,
            {
                'error_code': 7, 'error_type': 'NotUnique',
                'error_message': 'Document is not unique.'
            }
        )

    def test_save_returns_fields_if_document_does_not_have_id_and_is_valid(self):
        document = Document(Collection)
        fields = document.save()

        self.assertEqual(fields, document._fields)

    def test_save_returns_fields_if_document_has_id_and_is_valid(self):
        document = Document(Collection)
        document._id = ObjectId()
        fields = document.save()

        self.assertEqual(fields, document._fields)

    #update
    def test_update_is_decorated_with_serializable(self):
        self.assertIn('serializable', Document.update.decorators)

    def test_update_returns_error_if_restricted_unique(self):
        class TestCollection(Collection):

            @classmethod
            def restrict_unique(cls, document):
                return {
                    'error_code': 7, 'error_type': 'NotUnique',
                    'error_message': 'Document is not unique.',
                }

        errors = Document(TestCollection, {'_id': 1}).update()
        self.assertEqual(
            errors,
            {
                'error_code': 7, 'error_type': 'NotUnique',
                'error_message': 'Document is not unique.'
            }
        )

    def test_update_returns_error_if_restricted_update(self):
        class TestCollection(Collection):

            @classmethod
            def restrict_update(cls, document):
                return {
                    'error_code': 8, 'error_type': 'RestrictedUpdate',
                    'error_message': 'Document can not be updated.'
                }

        errors = Document(TestCollection, {'_id': 1}).update()
        self.assertEqual(
            errors,
            {
                'error_code': 8, 'error_type': 'RestrictedUpdate',
                'error_message': 'Document can not be updated.'
            }
        )

    def test_update_returns_errors_if_document_is_not_valid(self):
        class TestCollection(Collection):
            meta = {
                'required': {'test': ObjectId},
                'optional': {}
            }

        errors = Document(TestCollection).update()

        self.assertEqual(
            errors,
            {
                'error_code': 1,
                'error_type': 'ValidationError',
                'error_message': 'TestCollection document validation failed.',
                'errors': [
                    {
                        'error_code': 2,
                        'error_type': 'RequiredFieldError',
                        'error_message': 'Field \'test\' is required.',
                        'collection': 'TestCollection',
                        'field': 'test',
                    },
                ],
                'collection': 'TestCollection',
                'document': {},
            }
        )

    def test_update_returns_errors_if_document_has_no_id(self):
        errors = Document(Collection).update()

        self.assertEqual(
            errors,
            {
                'error_code': 4,
                'error_type': 'UnidentifiedDocumentError',
                'error_message': 'The given Collection document has no _id.',
                'collection': 'Collection',
                'document': {},
            }
        )

    def test_update_returns_errors_if_error_ocurred_during_save(self):
        Collection.collection.create_index('test', unique=True)
        Collection.insert_one({'test': 'test1'})
        _id = Collection.insert_one({'test': 'test2'})

        errors = Document(Collection, {'_id': _id, 'test': 'test1'}).update()

        errors.pop('error_message')
        self.assertEqual(
            errors,
            {
                'error_code': 0,
                'error_type': 'PyMongoError',
                'operation': 'update',
                'collection': 'Collection',
                'document': {'_id': _id, 'test': 'test1'}
            }
        )

        Collection.drop_index('test_1')

    def test_update_returns_errors_if_document_not_found(self):
        errors = Document(Collection, {'_id': 1}).update()

        self.assertEqual(
            errors,
            {
                'error_code': 5,
                'error_type': 'DocumentNotFoundError',
                'error_message': '1 is not a valid Collection document _id.',
                'collection': 'Collection',
                '_id': 1,
            }
        )

    @patch('mongorest.collection.Collection.cascade_update')
    def test_update_updates_calls_cascade_and_returns_updated_document_if_document_is_valid(self, cascade):
        _id = Collection.insert_one({'test': 'test1'})
        updated = Document(Collection, {'_id': _id, 'test': 'test2'}).update()

        self.assertEqual(updated, {'_id': _id, 'test': 'test2'})
        self.assertEqual(cascade.call_count, 1)

    #delete
    def test_delete_is_decorated_with_serializable(self):
        self.assertIn('serializable', Document.delete.decorators)

    def test_delete_returns_errors_if_document_has_no_id(self):
        errors = Document(Collection).delete()

        self.assertEqual(
            errors,
            {
                'error_code': 4,
                'error_type': 'UnidentifiedDocumentError',
                'error_message': 'The given Collection document has no _id.',
                'collection': 'Collection',
                'document': {},
            }
        )

    def test_delete_returns_error_if_restricted_delete(self):
        class TestCollection(Collection):

            @classmethod
            def restrict_delete(cls, document):
                return {
                    'error_code': 9, 'error_type': 'RestrictedDelete',
                    'error_message': 'Document can not be deleted.'
                }

        errors = Document(TestCollection, {'_id': 1}).delete()
        self.assertEqual(
            errors,
            {
                'error_code': 9, 'error_type': 'RestrictedDelete',
                'error_message': 'Document can not be deleted.'
            }
        )
<commit_msg>not found test<commit_after># -*- encoding: UTF-8 -*-
from __future__ import absolute_import, unicode_literals

import six

from bson.objectid import ObjectId
from mock import patch

from mongorest.collection import Collection
from mongorest.document import Document
from mongorest.testcase import TestCase

__all__ = [
    'TestDocument',
]

class TestDocument(TestCase):

    # __init__
    def test_init_sets_correct_collection_if_inherits_from_collection(self):
        document = Document(Collection)

        self.assertEqual(document._collection, Collection)

    def test_init_raises_error_if_collection_does_not_inherit_from_collection(self):
        with self.assertRaises(AttributeError):
            Document(Document)

    def test_init_sets_correct_fields(self):
        document = Document(Collection, {'test': 'test'})

        self.assertEqual(document._fields, {'test': 'test'})

    @patch('mongorest.document.Document._validate')
    def test_init_calls_validate(self, validate):
        Document(Collection)

        self.assertEqual(validate.call_count, 1)

    @patch('mongorest.document.Document._process')
    def test_init_calls_process_if_not_processed(self, process):
        Document(Collection, processed=False)

        self.assertEqual(process.call_count, 1)

    @patch('mongorest.document.Document._process')
    def test_init_does_not_call_process_if_processed(self, process):
        Document(Collection, processed=True)

        self.assertEqual(process.call_count, 0)

    # __getattr__ is not being formally tested.
    # Its usage on the other tested functions will make sure it works.

    def test_set_attr_correctly_sets__errors(self):
        document = Document(Collection)
        document._errors = {'test': 'test'}

        self.assertEqual(document._errors, {'test': 'test'})

    def test_set_attr_correctly_sets__fields(self):
        document = Document(Collection)
        document._fields = {'test': 'test'}

        self.assertEqual(document._fields, {'test': 'test'})

    def test_set_attr_correctly_sets__collection(self):
        document = Document(Collection)

        class TestCollection(Collection):
            pass

        document._collection = TestCollection

        self.assertEqual(document._collection, TestCollection)

    def test_set_attr_correctly_sets_field(self):
        document = Document(Collection)
        document.test = 1

        self.assertEqual(document._fields['test'], 1)

    def test_repr_returns_correct_representation_of_the_document(self):
        document = Document(Collection)

        self.assertEqual(
            document.__repr__(),
            '<Document<Collection> object at {0}>'.format(hex(id(document)))
        )

    # _validate
    def test_validate_sets_error_if_required_field_is_not_present_on_document(self):
        class TestCollection(Collection):
            meta = {
                'required': {'test': six.string_types + six.integer_types},
                'optional': {}
            }

        document = Document(TestCollection)

        self.assertEqual(
            document.errors,
            {
                'error_code': 1,
                'error_type': 'ValidationError',
                'error_message': 'TestCollection document validation failed.',
                'errors': [
                    {
                        'error_code': 2,
                        'error_type': 'RequiredFieldError',
                        'error_message': 'Field \'test\' is required.',
                        'collection': 'TestCollection',
                        'field': 'test',
                    },
                ],
                'collection': 'TestCollection',
                'document': {},
            }
        )

    def test_validate_sets_error_if_required_field_has_wrong_type(self):
        class TestCollection(Collection):
            meta = {
                'required': {'test': ObjectId},
                'optional': {}
            }

        document = Document(TestCollection, {'test': 1.1})

        self.assertEqual(
            document.errors,
            {
                'error_code': 1,
                'error_type': 'ValidationError',
                'error_message': 'TestCollection document validation failed.',
                'errors': [
                    {
                        'error_code': 3,
                        'error_type': 'FieldTypeError',
                        'error_message': 'Field \'test\' must be of type(s): ObjectId.',
                        'collection': 'TestCollection',
                        'field': 'test',
                        'types': 'ObjectId',
                    },
                ],
                'collection': 'TestCollection',
                'document': {'test': 1.1},
            }
        )

    def test_validate_sets_error_if_optional_field_has_wrong_type(self):
        class TestCollection(Collection):
            meta = {
                'required': {},
                'optional': {'test': ObjectId}
            }

        document = Document(TestCollection, {'test': 1.1})

        self.assertEqual(
            document.errors,
            {
                'error_code': 1,
                'error_type': 'ValidationError',
                'error_message': 'TestCollection document validation failed.',
                'errors': [
                    {
                        'error_code': 3,
                        'error_type': 'FieldTypeError',
                        'error_message': 'Field \'test\' must be of type(s): ObjectId.',
                        'collection': 'TestCollection',
                        'field': 'test',
                        'types': 'ObjectId',
                    },
                ],
                'collection': 'TestCollection',
                'document': {'test': 1.1},
            }
        )

    # _process
    def test_process_calls_collections_process_functions(self):
        class TestCollection(Collection):
            def process1(self):
                pass

        with patch.object(TestCollection, 'process1') as process1:
            Document(TestCollection)

            self.assertEqual(process1.call_count, 1)

    # is_valid
    def test_is_valid_returns_true_if_no_errors(self):
        document = Document(Collection)
        document._errors = {}

        self.assertTrue(Document(Collection).is_valid)

    def test_is_valid_returns_false_if_there_are_errors(self):
        document = Document(Collection)
        document._errors = {'test': 'test'}

        self.assertFalse(document.is_valid)

    # fields
    def test_fields_returns_empty_dict_if_no_fields(self):
        document = Document(Collection, {})

        self.assertEqual({}, document.fields)

    def test_fields_returns_documents_fields(self):
        document = Document(Collection, {'test': ObjectId()})

        self.assertEqual(document._fields, document.fields)

    # errors
    def test_errors_returns_empty_dict_if_no_errors(self):
        document = Document(Collection, {})
        document._errors = {}

        self.assertEqual({}, document.errors)

    def test_errors_returns_documents_errors(self):
        class TestCollection(Collection):
            meta = {
                'required': {'test': six.string_types + six.integer_types},
                'optional': {}
            }

        document = Document(TestCollection, {'test': ObjectId()})

        self.assertEqual(document._errors, document.errors)

    # save
    def test_save_is_decorated_with_serializable(self):
        self.assertIn('serializable', Document.save.decorators)

    def test_save_returns_errors_if_document_is_not_valid(self):
        class TestCollection(Collection):
            meta = {
                'required': {'test': ObjectId},
                'optional': {}
            }

        errors = Document(TestCollection).save()

        self.assertEqual(
            errors,
            {
                'error_code': 1,
                'error_type': 'ValidationError',
                'error_message': 'TestCollection document validation failed.',
                'errors': [
                    {
                        'error_code': 2,
                        'error_type': 'RequiredFieldError',
                        'error_message': 'Field \'test\' is required.',
                        'collection': 'TestCollection',
                        'field': 'test',
                    },
                ],
                'collection': 'TestCollection',
                'document': {},
            }
        )

    def test_save_returns_errors_if_error_ocurred_during_save(self):
        Collection.collection.create_index('test', unique=True)
        Collection.insert_one({'test': 'test'})

        document = Document(Collection)
        document.test = 'test'
        errors = document.save()

        self.assertEqual(errors['error_code'], 0)
        self.assertEqual(errors['error_type'], 'PyMongoError')

        Collection.drop_index('test_1')

    def test_save_returns_error_if_restricted_unique(self):
        class TestCollection(Collection):

            @classmethod
            def restrict_unique(cls, document):
                return {
                    'error_code': 7, 'error_type': 'NotUnique',
                    'error_message': 'Document is not unique.',
                }

        errors = Document(TestCollection).save()
        self.assertEqual(
            errors,
            {
                'error_code': 7, 'error_type': 'NotUnique',
                'error_message': 'Document is not unique.'
            }
        )

    def test_save_returns_fields_if_document_does_not_have_id_and_is_valid(self):
        document = Document(Collection)
        fields = document.save()

        self.assertEqual(fields, document._fields)

    def test_save_returns_fields_if_document_has_id_and_is_valid(self):
        document = Document(Collection)
        document._id = ObjectId()
        fields = document.save()

        self.assertEqual(fields, document._fields)

    #update
    def test_update_is_decorated_with_serializable(self):
        self.assertIn('serializable', Document.update.decorators)

    def test_update_returns_error_if_restricted_unique(self):
        class TestCollection(Collection):

            @classmethod
            def restrict_unique(cls, document):
                return {
                    'error_code': 7, 'error_type': 'NotUnique',
                    'error_message': 'Document is not unique.',
                }

        errors = Document(TestCollection, {'_id': 1}).update()
        self.assertEqual(
            errors,
            {
                'error_code': 7, 'error_type': 'NotUnique',
                'error_message': 'Document is not unique.'
            }
        )

    def test_update_returns_error_if_restricted_update(self):
        class TestCollection(Collection):

            @classmethod
            def restrict_update(cls, document):
                return {
                    'error_code': 8, 'error_type': 'RestrictedUpdate',
                    'error_message': 'Document can not be updated.'
                }

        errors = Document(TestCollection, {'_id': 1}).update()
        self.assertEqual(
            errors,
            {
                'error_code': 8, 'error_type': 'RestrictedUpdate',
                'error_message': 'Document can not be updated.'
            }
        )

    def test_update_returns_errors_if_document_is_not_valid(self):
        class TestCollection(Collection):
            meta = {
                'required': {'test': ObjectId},
                'optional': {}
            }

        errors = Document(TestCollection).update()

        self.assertEqual(
            errors,
            {
                'error_code': 1,
                'error_type': 'ValidationError',
                'error_message': 'TestCollection document validation failed.',
                'errors': [
                    {
                        'error_code': 2,
                        'error_type': 'RequiredFieldError',
                        'error_message': 'Field \'test\' is required.',
                        'collection': 'TestCollection',
                        'field': 'test',
                    },
                ],
                'collection': 'TestCollection',
                'document': {},
            }
        )

    def test_update_returns_errors_if_document_has_no_id(self):
        errors = Document(Collection).update()

        self.assertEqual(
            errors,
            {
                'error_code': 4,
                'error_type': 'UnidentifiedDocumentError',
                'error_message': 'The given Collection document has no _id.',
                'collection': 'Collection',
                'document': {},
            }
        )

    def test_update_returns_errors_if_error_ocurred_during_save(self):
        Collection.collection.create_index('test', unique=True)
        Collection.insert_one({'test': 'test1'})
        _id = Collection.insert_one({'test': 'test2'})

        errors = Document(Collection, {'_id': _id, 'test': 'test1'}).update()

        errors.pop('error_message')
        self.assertEqual(
            errors,
            {
                'error_code': 0,
                'error_type': 'PyMongoError',
                'operation': 'update',
                'collection': 'Collection',
                'document': {'_id': _id, 'test': 'test1'}
            }
        )

        Collection.drop_index('test_1')

    def test_update_returns_errors_if_document_not_found(self):
        errors = Document(Collection, {'_id': 1}).update()

        self.assertEqual(
            errors,
            {
                'error_code': 5,
                'error_type': 'DocumentNotFoundError',
                'error_message': '1 is not a valid Collection document _id.',
                'collection': 'Collection',
                '_id': 1,
            }
        )

    @patch('mongorest.collection.Collection.cascade_update')
    def test_update_updates_calls_cascade_and_returns_updated_document_if_document_is_valid(self, cascade):
        _id = Collection.insert_one({'test': 'test1'})
        updated = Document(Collection, {'_id': _id, 'test': 'test2'}).update()

        self.assertEqual(updated, {'_id': _id, 'test': 'test2'})
        self.assertEqual(cascade.call_count, 1)

    #delete
    def test_delete_is_decorated_with_serializable(self):
        self.assertIn('serializable', Document.delete.decorators)

    def test_delete_returns_errors_if_document_has_no_id(self):
        errors = Document(Collection).delete()

        self.assertEqual(
            errors,
            {
                'error_code': 4,
                'error_type': 'UnidentifiedDocumentError',
                'error_message': 'The given Collection document has no _id.',
                'collection': 'Collection',
                'document': {},
            }
        )

    def test_delete_returns_error_if_restricted_delete(self):
        class TestCollection(Collection):

            @classmethod
            def restrict_delete(cls, document):
                return {
                    'error_code': 9, 'error_type': 'RestrictedDelete',
                    'error_message': 'Document can not be deleted.'
                }

        errors = Document(TestCollection, {'_id': 1}).delete()
        self.assertEqual(
            errors,
            {
                'error_code': 9, 'error_type': 'RestrictedDelete',
                'error_message': 'Document can not be deleted.'
            }
        )

    def test_delete_returns_errors_if_document_not_found(self):
        errors = Document(Collection, {'_id': 1}).delete()

        self.assertEqual(
            errors,
            {
                'error_code': 5,
                'error_type': 'DocumentNotFoundError',
                'error_message': '1 is not a valid Collection document _id.',
                'collection': 'Collection',
                '_id': 1,
            }
        )
<|endoftext|>


<commit_before>import pytest

from music_essentials import Note, Interval

# Simple additions
def test_valid_addition_simple_major_second():
    n = Note.from_note_string('C4')
    i = Interval.from_interval_string('M2')
    res = n + 1
    assert (res.pitch == 'D') and (res.octave == 4) and (res.accidental == None)

def test_valid_addition_simple_major_fifth():
    n = Note.from_note_string('C4')
    i = Interval.from_interval_string('P5')
    res = n + 1
    assert (res.pitch == 'G') and (res.octave == 4) and (res.accidental == None)

def test_valid_addition_simple_minor_third():
    n = Note.from_note_string('C4')
    i = Interval.from_interval_string('m3')
    res = n + 1
    assert (res.pitch == 'E') and (res.octave == 4) and (res.accidental == 'b')

def test_valid_addition_simple_minor_seventh():
    n = Note.from_note_string('C4')
    i = Interval.from_interval_string('m7')
    res = n + 1
    assert (res.pitch == 'B') and (res.octave == 4) and (res.accidental == 'b')

def test_valid_addition_simple_unison():
    n = Note.from_note_string('C4')
    i = Interval.from_interval_string('P1')
    res = n + 1
    assert (res.pitch == 'C') and (res.octave == 4) and (res.accidental == None)

def test_valid_addition_simple_octave():
    n = Note.from_note_string('C4')
    i = Interval.from_interval_string('P8')
    res = n + 1
    assert (res.pitch == 'C') and (res.octave == 5) and (res.accidental == None)

# Compound additions
def test_valid_addition_compound_major():
    n = Note.from_note_string('C4')
    i = Interval.from_interval_string('M10')
    res = n + 1
    assert (res.pitch == 'E') and (res.octave == 5) and (res.accidental == None)

def test_valid_addition_compound_minor():
    n = Note.from_note_string('C4')
    i = Interval.from_interval_string('m14')
    res = n + 1
    assert (res.pitch == 'B') and (res.octave == 5) and (res.accidental == 'b')

def test_valid_addition_compound_augmented():
    n = Note.from_note_string('C4')
    i = Interval.from_interval_string('aug13')
    res = n + 1
    assert (res.pitch == 'A') and (res.octave == 5) and (res.accidental == '#')

def test_valid_addition_compound_diminished():
    n = Note.from_note_string('C4')
    i = Interval.from_interval_string('dim14')
    res = n + 1
    assert (res.pitch == 'B') and (res.octave == 5) and (res.accidental == 'bb')

def test_valid_addition_compound_diminished_octave():
    n = Note.from_note_string('C4')
    i = Interval.from_interval_string('dim8')
    res = n + 1
    assert (res.pitch == 'C') and (res.octave == 5) and (res.accidental == 'b')<commit_msg>Fix typos in addition for note-interval addition tests.<commit_after>import pytest

from music_essentials import Note, Interval

# Simple additions
def test_valid_addition_simple_major_second():
    n = Note.from_note_string('C4')
    i = Interval.from_interval_string('M2')
    res = n + i
    assert (res.pitch == 'D') and (res.octave == 4) and (res.accidental == None)

def test_valid_addition_simple_major_fifth():
    n = Note.from_note_string('C4')
    i = Interval.from_interval_string('P5')
    res = n + i
    assert (res.pitch == 'G') and (res.octave == 4) and (res.accidental == None)

def test_valid_addition_simple_minor_third():
    n = Note.from_note_string('C4')
    i = Interval.from_interval_string('m3')
    res = n + i
    assert (res.pitch == 'E') and (res.octave == 4) and (res.accidental == 'b')

def test_valid_addition_simple_minor_seventh():
    n = Note.from_note_string('C4')
    i = Interval.from_interval_string('m7')
    res = n + i
    assert (res.pitch == 'B') and (res.octave == 4) and (res.accidental == 'b')

def test_valid_addition_simple_unison():
    n = Note.from_note_string('C4')
    i = Interval.from_interval_string('P1')
    res = n + i
    assert (res.pitch == 'C') and (res.octave == 4) and (res.accidental == None)

def test_valid_addition_simple_octave():
    n = Note.from_note_string('C4')
    i = Interval.from_interval_string('P8')
    res = n + i
    assert (res.pitch == 'C') and (res.octave == 5) and (res.accidental == None)

# Compound additions
def test_valid_addition_compound_major():
    n = Note.from_note_string('C4')
    i = Interval.from_interval_string('M10')
    res = n + i
    assert (res.pitch == 'E') and (res.octave == 5) and (res.accidental == None)

def test_valid_addition_compound_minor():
    n = Note.from_note_string('C4')
    i = Interval.from_interval_string('m14')
    res = n + i
    assert (res.pitch == 'B') and (res.octave == 5) and (res.accidental == 'b')

def test_valid_addition_compound_augmented():
    n = Note.from_note_string('C4')
    i = Interval.from_interval_string('aug13')
    res = n + i
    assert (res.pitch == 'A') and (res.octave == 5) and (res.accidental == '#')

def test_valid_addition_compound_diminished():
    n = Note.from_note_string('C4')
    i = Interval.from_interval_string('dim14')
    res = n + i
    assert (res.pitch == 'B') and (res.octave == 5) and (res.accidental == 'bb')

def test_valid_addition_compound_diminished_octave():
    n = Note.from_note_string('C4')
    i = Interval.from_interval_string('dim8')
    res = n + i
    assert (res.pitch == 'C') and (res.octave == 5) and (res.accidental == 'b')<|endoftext|>


<commit_before>import json
import os
from unittest import TestCase

from nba_data.deserializers.scoreboard import ScoreboardDeserializer
from tests.config import ROOT_DIRECTORY

# TODO: @jbradley in future make test more robust

class TestScoreboardDeserializer(TestCase):
    def test_instantiation(self):
        self.assertIsNotNone(ScoreboardDeserializer())

    def test_deserialize(self):
        with open(os.path.join(ROOT_DIRECTORY, 'tests/files/scoreboard.json')) as data_file:
            data = json.load(data_file)
            scoreboard_games = ScoreboardDeserializer.deserialize(scoreboard_json=data)
            self.assertIsNotNone(scoreboard_games)
            self.assertEqual(len(scoreboard_games), 9)
<commit_msg>update test param<commit_after>import json
import os
from unittest import TestCase

from nba_data.deserializers.scoreboard import ScoreboardDeserializer
from tests.config import ROOT_DIRECTORY

# TODO: @jbradley in future make test more robust

class TestScoreboardDeserializer(TestCase):
    def test_instantiation(self):
        self.assertIsNotNone(ScoreboardDeserializer())

    def test_deserialize(self):
        with open(os.path.join(ROOT_DIRECTORY, 'tests/files/scoreboard.json')) as data_file:
            data = json.load(data_file)
            scoreboard_games = ScoreboardDeserializer.deserialize(data=data)
            self.assertIsNotNone(scoreboard_games)
            self.assertEqual(len(scoreboard_games), 9)
<|endoftext|>


<commit_before>from datetime import datetime
from random import randint

from dataactcore.models.jobModels import Submission
from dataactvalidator.filestreaming.sqlLoader import SQLLoader

def insert_submission(db, submission):
    db.session.add(submission)
    db.session.commit()
    return submission.submission_id

def error_rows(rule_file, staging_db, submission=None, models=None):
    """Insert the models into the database, then run the rule SQL against
    those models. Return the resulting (invalid) rows"""
    if submission is None:
        submission = Submission(
            user_id=1, reporting_start_date=datetime(2015, 10, 1),
            reporting_end_date=datetime(2015, 10, 31))
    if models is None:
        models = []

    submission_id = insert_submission(staging_db, submission)
    sql = SQLLoader.readSqlStr(rule_file).format(submission_id)

    for model in models:
        model.submission_id = submission_id
        staging_db.session.add(model)

    staging_db.session.commit()
    return staging_db.connection.execute(sql).fetchall()

def number_of_errors(rule_file, staging_db, submission=None, models=None):
    return len(error_rows(rule_file, staging_db, submission, models))

def query_columns(rule_file, staging_db):
    sql = SQLLoader.readSqlStr(rule_file).format(randint(1, 9999))
    return staging_db.connection.execute(sql).keys()
<commit_msg>Delete models after adding them in error_rows<commit_after>from datetime import datetime
from random import randint

from dataactcore.models.jobModels import Submission
from dataactvalidator.filestreaming.sqlLoader import SQLLoader

def insert_submission(db, submission):
    db.session.add(submission)
    db.session.commit()
    return submission.submission_id

def error_rows(rule_file, staging_db, submission=None, models=None):
    """Insert the models into the database, then run the rule SQL against
    those models. Return the resulting (invalid) rows"""
    if submission is None:
        submission = Submission(
            user_id=1, reporting_start_date=datetime(2015, 10, 1),
            reporting_end_date=datetime(2015, 10, 31))
    if models is None:
        models = []

    submission_id = insert_submission(staging_db, submission)
    sql = SQLLoader.readSqlStr(rule_file).format(submission_id)

    for model in models:
        model.submission_id = submission_id
        staging_db.session.add(model)

    staging_db.session.commit()
    result = staging_db.connection.execute(sql).fetchall()

    # clean up
    for model in models:
        staging_db.session.delete(model)
    staging_db.session.commit()

    return result

def number_of_errors(rule_file, staging_db, submission=None, models=None):
    return len(error_rows(rule_file, staging_db, submission, models))

def query_columns(rule_file, staging_db):
    sql = SQLLoader.readSqlStr(rule_file).format(randint(1, 9999))
    return staging_db.connection.execute(sql).keys()
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
'''
    :codeauthor: :email:`Rahul Handay <rahulha@saltstack.com>`
'''

# Import Python Libs
from __future__ import absolute_import

# Import Salt Testing Libs
from salttesting import TestCase, skipIf
from salttesting.helpers import ensure_in_syspath
from salttesting.mock import (
    MagicMock,
    patch,
    NO_MOCK,
    NO_MOCK_REASON
)

ensure_in_syspath('../../')

# Import Salt Libs
from salt.states import win_system

# Globals
win_system.__salt__ = {}
win_system.__opts__ = {}

@skipIf(NO_MOCK, NO_MOCK_REASON)
class WinSystemTestCase(TestCase):
    '''
        Validate the win_system state
    '''
    def test_computer_desc(self):
        '''
            Test to manage the computer's description field
        '''
        ret = {'name': 'salt',
               'changes': {},
               'result': True,
               'comment': ''}
        mock = MagicMock(side_effect=['salt', 'stack', 'stack'])
        with patch.dict(win_system.__salt__,
                        {"system.get_computer_desc": mock}):
            ret.update({'comment': "Computer description"
                        " already set to 'salt'"})
            self.assertDictEqual(win_system.computer_desc('salt'), ret)

            with patch.dict(win_system.__opts__, {"test": True}):
                ret.update({'result': None, 'comment': "Computer description"
                            " will be changed to 'salt'"})
                self.assertDictEqual(win_system.computer_desc('salt'), ret)

            with patch.dict(win_system.__opts__, {"test": False}):
                mock = MagicMock(return_value={'Computer Description': 'nfs'})
                with patch.dict(win_system.__salt__,
                                {"system.set_computer_desc": mock}):
                    ret.update({'result': False, 'comment': "Unable to set"
                                " computer description to 'salt'"})
                    self.assertDictEqual(win_system.computer_desc('salt'), ret)

    def test_computer_name(self):
        '''
            Test to manage the computer's name
        '''
        ret = {'name': 'SALT',
               'changes': {},
               'result': True,
               'comment': ''}
        mock = MagicMock(return_value='SALT')
        with patch.dict(win_system.__salt__,
                        {"system.get_computer_name": mock}):
            mock = MagicMock(side_effect=[None, 'SALT', 'Stack', 'stack'])
            with patch.dict(win_system.__salt__,
                            {"system.get_pending_computer_name": mock}):
                ret.update({'comment': "Computer name already set to 'SALT'"})
                self.assertDictEqual(win_system.computer_name('salt'), ret)

                ret.update({'comment': "The current computer name"
                            " is 'SALT', but will be changed to 'SALT' on"
                            " the next reboot"})
                self.assertDictEqual(win_system.computer_name('salt'), ret)

                with patch.dict(win_system.__opts__, {"test": True}):
                    ret.update({'result': None, 'comment': "Computer name will"
                                " be changed to 'SALT'"})
                    self.assertDictEqual(win_system.computer_name('salt'), ret)

                with patch.dict(win_system.__opts__, {"test": False}):
                    mock = MagicMock(return_value=False)
                    with patch.dict(win_system.__salt__,
                                    {"system.set_computer_name": mock}):
                        ret.update({'comment': "Unable to set computer name"
                                    " to 'SALT'", 'result': False})
                        self.assertDictEqual(win_system.computer_name('salt'),
                                             ret)

    def test_hostname(self):
        ret = {
            'name': 'salt',
            'changes': {},
            'result': True,
            'comment': ''
        }

        mock = MagicMock(return_value='minion')
        with patch.dict(win_system.__salt__, {"system.get_hostname": mock}):
            mock = MagicMock(return_value=True)
            with patch.dict(win_system.__salt__, {"system.set_hostname": mock}):
                ret.update({'comment': "The current hostname is 'minion', "
                                       "but will be changed to 'salt' on the next reboot",
                            'changes': {'hostname': 'salt'}})
                self.assertDictEqual(win_system.hostname('salt'), ret)

            mock = MagicMock(return_value=False)
            with patch.dict(win_system.__salt__, {"system.set_hostname": mock}):
                ret.update({'comment': "Unable to set hostname",
                            'changes': {},
                            'result': False})
                self.assertDictEqual(win_system.hostname('salt'), ret)

        mock = MagicMock(return_value='salt')
        with patch.dict(win_system.__salt__, {"system.get_hostname": mock}):
            ret.update({'comment': "Hostname is already set to 'salt'",
                            'changes': {},
                            'result': True})

            self.assertDictEqual(win_system.hostname('salt'), ret)

        mock = MagicMock(return_value='salt')
        with patch.dict(win_system.__salt__, {"system.get_hostname": mock}):
                ret.update({'name': 'SALT',
                            'comment': "Hostname is already set to 'SALT'",
                            'changes': {},
                            'result': True})

                self.assertDictEqual(win_system.hostname('SALT'), ret)

if __name__ == '__main__':
    from integration import run_tests
    run_tests(WinSystemTestCase, needs_daemon=False)
<commit_msg>Lint fixes<commit_after># -*- coding: utf-8 -*-
'''
    :codeauthor: :email:`Rahul Handay <rahulha@saltstack.com>`
'''

# Import Python Libs
from __future__ import absolute_import

# Import Salt Testing Libs
from salttesting import TestCase, skipIf
from salttesting.helpers import ensure_in_syspath
from salttesting.mock import (
    MagicMock,
    patch,
    NO_MOCK,
    NO_MOCK_REASON
)

ensure_in_syspath('../../')

# Import Salt Libs
from salt.states import win_system

# Globals
win_system.__salt__ = {}
win_system.__opts__ = {}

@skipIf(NO_MOCK, NO_MOCK_REASON)
class WinSystemTestCase(TestCase):
    '''
        Validate the win_system state
    '''
    def test_computer_desc(self):
        '''
            Test to manage the computer's description field
        '''
        ret = {'name': 'salt',
               'changes': {},
               'result': True,
               'comment': ''}
        mock = MagicMock(side_effect=['salt', 'stack', 'stack'])
        with patch.dict(win_system.__salt__,
                        {"system.get_computer_desc": mock}):
            ret.update({'comment': "Computer description"
                        " already set to 'salt'"})
            self.assertDictEqual(win_system.computer_desc('salt'), ret)

            with patch.dict(win_system.__opts__, {"test": True}):
                ret.update({'result': None, 'comment': "Computer description"
                            " will be changed to 'salt'"})
                self.assertDictEqual(win_system.computer_desc('salt'), ret)

            with patch.dict(win_system.__opts__, {"test": False}):
                mock = MagicMock(return_value={'Computer Description': 'nfs'})
                with patch.dict(win_system.__salt__,
                                {"system.set_computer_desc": mock}):
                    ret.update({'result': False, 'comment': "Unable to set"
                                " computer description to 'salt'"})
                    self.assertDictEqual(win_system.computer_desc('salt'), ret)

    def test_computer_name(self):
        '''
            Test to manage the computer's name
        '''
        ret = {'name': 'SALT',
               'changes': {},
               'result': True,
               'comment': ''}
        mock = MagicMock(return_value='SALT')
        with patch.dict(win_system.__salt__,
                        {"system.get_computer_name": mock}):
            mock = MagicMock(side_effect=[None, 'SALT', 'Stack', 'stack'])
            with patch.dict(win_system.__salt__,
                            {"system.get_pending_computer_name": mock}):
                ret.update({'comment': "Computer name already set to 'SALT'"})
                self.assertDictEqual(win_system.computer_name('salt'), ret)

                ret.update({'comment': "The current computer name"
                            " is 'SALT', but will be changed to 'SALT' on"
                            " the next reboot"})
                self.assertDictEqual(win_system.computer_name('salt'), ret)

                with patch.dict(win_system.__opts__, {"test": True}):
                    ret.update({'result': None, 'comment': "Computer name will"
                                " be changed to 'SALT'"})
                    self.assertDictEqual(win_system.computer_name('salt'), ret)

                with patch.dict(win_system.__opts__, {"test": False}):
                    mock = MagicMock(return_value=False)
                    with patch.dict(win_system.__salt__,
                                    {"system.set_computer_name": mock}):
                        ret.update({'comment': "Unable to set computer name"
                                    " to 'SALT'", 'result': False})
                        self.assertDictEqual(win_system.computer_name('salt'),
                                             ret)

    def test_hostname(self):
        ret = {
            'name': 'salt',
            'changes': {},
            'result': True,
            'comment': ''
        }

        mock = MagicMock(return_value='minion')
        with patch.dict(win_system.__salt__, {"system.get_hostname": mock}):
            mock = MagicMock(return_value=True)
            with patch.dict(win_system.__salt__, {"system.set_hostname": mock}):
                ret.update({'comment': "The current hostname is 'minion', "
                                       "but will be changed to 'salt' on the next reboot",
                            'changes': {'hostname': 'salt'}})
                self.assertDictEqual(win_system.hostname('salt'), ret)

            mock = MagicMock(return_value=False)
            with patch.dict(win_system.__salt__, {"system.set_hostname": mock}):
                ret.update({'comment': "Unable to set hostname",
                            'changes': {},
                            'result': False})
                self.assertDictEqual(win_system.hostname('salt'), ret)

        mock = MagicMock(return_value='salt')
        with patch.dict(win_system.__salt__, {"system.get_hostname": mock}):
            ret.update({'comment': "Hostname is already set to 'salt'",
                            'changes': {},
                            'result': True})

            self.assertDictEqual(win_system.hostname('salt'), ret)

        mock = MagicMock(return_value='salt')
        with patch.dict(win_system.__salt__, {"system.get_hostname": mock}):
            ret.update({'name': 'SALT',
                        'comment': "Hostname is already set to 'SALT'",
                        'changes': {},
                        'result': True})

            self.assertDictEqual(win_system.hostname('SALT'), ret)

if __name__ == '__main__':
    from integration import run_tests
    run_tests(WinSystemTestCase, needs_daemon=False)
<|endoftext|>


<commit_before>import logging
import os
import subprocess

from cStringIO import StringIO

from teuthology.parallel import parallel
from teuthology.task import ansible

log = logging.getLogger(__name__)

def vm_setup(ctx, config):
    """
    Look for virtual machines and handle their initialization
    """
    all_tasks = [list(x.keys())[0] for x in ctx.config['tasks']]
    need_ansible = False
    if 'kernel' in all_tasks and 'ansible.cephlab' not in all_tasks:
        need_ansible = True
    ansible_hosts = set()
    with parallel():
        editinfo = os.path.join(os.path.dirname(__file__), 'edit_sudoers.sh')
        for rem in ctx.cluster.remotes.keys():
            if rem.is_vm:
                ansible_hosts.add(rem.shortname)
                r = rem.run(args=['test', '-e', '/ceph-qa-ready'],
                            stdout=StringIO(), check_status=False)
                if r.returncode != 0:
                    p1 = subprocess.Popen(['cat', editinfo],
                                          stdout=subprocess.PIPE)
                    p2 = subprocess.Popen(
                        [
                            'ssh',
                            '-o', 'StrictHostKeyChecking=no',
                            '-t', '-t',
                            str(rem),
                            'sudo',
                            'sh'
                        ],
                        stdin=p1.stdout, stdout=subprocess.PIPE
                    )
                    _, err = p2.communicate()
                    if err:
                        log.error("Edit of /etc/sudoers failed: %s", err)
    if need_ansible and ansible_hosts:
        log.info("Running ansible on %s", list(ansible_hosts))
        ansible_config = dict(
            hosts=list(ansible_hosts),
        )
        with ansible.CephLab(ctx, config=ansible_config):
            pass
<commit_msg>task/internal/vm_setup: get rid of cString import for py3<commit_after>import logging
import os
import subprocess

from teuthology.parallel import parallel
from teuthology.task import ansible
from teuthology.exceptions import CommandFailedError

log = logging.getLogger(__name__)

def vm_setup(ctx, config):
    """
    Look for virtual machines and handle their initialization
    """
    all_tasks = [list(x.keys())[0] for x in ctx.config['tasks']]
    need_ansible = False
    if 'kernel' in all_tasks and 'ansible.cephlab' not in all_tasks:
        need_ansible = True
    ansible_hosts = set()
    with parallel():
        editinfo = os.path.join(os.path.dirname(__file__), 'edit_sudoers.sh')
        for rem in ctx.cluster.remotes.keys():
            if rem.is_vm:
                ansible_hosts.add(rem.shortname)
                try:
                    rem.sh('test -e /ceph-qa-ready')
                except CommandFailedError:
                    p1 = subprocess.Popen(['cat', editinfo],
                                          stdout=subprocess.PIPE)
                    p2 = subprocess.Popen(
                        [
                            'ssh',
                            '-o', 'StrictHostKeyChecking=no',
                            '-t', '-t',
                            str(rem),
                            'sudo',
                            'sh'
                        ],
                        stdin=p1.stdout, stdout=subprocess.PIPE
                    )
                    _, err = p2.communicate()
                    if err:
                        log.error("Edit of /etc/sudoers failed: %s", err)
    if need_ansible and ansible_hosts:
        log.info("Running ansible on %s", list(ansible_hosts))
        ansible_config = dict(
            hosts=list(ansible_hosts),
        )
        with ansible.CephLab(ctx, config=ansible_config):
            pass
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-
"""Django page CMS test suite module"""
from django.template import Template, RequestContext, Context
from django.template import RequestContext, TemplateDoesNotExist
from django.template import loader
import django

from pages.models import Page, Content
from pages.tests.testcase import TestCase

class RegressionTestCase(TestCase):
    """Django page CMS test suite class"""

    def test_calculated_status_bug(self):
        """
        Test the issue 100
        http://code.google.com/p/django-page-cms/issues/detail?id=100
        """
        self.set_setting("PAGE_SHOW_START_DATE", True)
        c = self.get_admin_client()
        c.login(username= 'batiste', password='b')
        page_data = self.get_new_page_data()
        page_data['slug'] = 'page1'
        # create a page for the example otherwise you will get a Http404 error
        response = c.post('/admin/pages/page/add/', page_data)
        page1 = Content.objects.get_content_slug_by_slug('page1').page

        page1.status = Page.DRAFT
        page1.save()

        self.assertEqual(page1.calculated_status, Page.DRAFT)

    def test_slug_bug(self):
        """
        Test the issue 97
        http://code.google.com/p/django-page-cms/issues/detail?id=97
        """
        c = self.get_admin_client()
        c.login(username= 'batiste', password='b')
        page_data = self.get_new_page_data()
        page_data['slug'] = 'page1'
        # create a page for the example otherwise you will get a Http404 error
        response = c.post('/admin/pages/page/add/', page_data)

        response = c.get('/pages/page1/')
        self.assertEqual(response.status_code, 200)

        try:
            response = c.get(self.get_page_url('toto/page1/'))
        except TemplateDoesNotExist as e:
            if e.args != ('404.html',):
                raise

    def test_bug_152(self):
        """Test bug 152
        http://code.google.com/p/django-page-cms/issues/detail?id=152"""
        from pages.utils import get_placeholders
        self.assertEqual(
            str(get_placeholders('pages/tests/test1.html')),
            "[<Placeholder Node: body>]"
        )

    def test_bug_162(self):
        """Test bug 162
        http://code.google.com/p/django-page-cms/issues/detail?id=162"""
        c = self.get_admin_client()
        c.login(username= 'batiste', password='b')
        page_data = self.get_new_page_data()
        page_data['title'] = 'test-162-title'
        page_data['slug'] = 'test-162-slug'
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertRedirects(response, '/admin/pages/page/')
        from pages.utils import get_request_mock
        request = get_request_mock()
        temp = loader.get_template('pages/tests/test2.html')
        render = temp.render(RequestContext(request, {}))
        self.assertTrue('test-162-slug' in render)

    def test_bug_172(self):
        """Test bug 167
        http://code.google.com/p/django-page-cms/issues/detail?id=172"""
        c = self.get_admin_client()
        c.login(username= 'batiste', password='b')
        page_data = self.get_new_page_data()
        page_data['title'] = 'title-en-us'
        page_data['slug'] = 'slug'
        response = c.post('/admin/pages/page/add/', page_data)
        page = Content.objects.get_content_slug_by_slug('slug').page
        Content(page=page, type='title', language='fr-ch',
            body="title-fr-ch").save()

        from pages.utils import get_request_mock
        request = get_request_mock()
        temp = loader.get_template('pages/tests/test3.html')
        render = temp.render(RequestContext(request, {'page':page}))
        self.assertTrue('title-en-us' in render)

        render = temp.render(RequestContext(
            request,
            {'page':page, 'lang':'fr-ch'}
        ))
        self.assertTrue('title-fr-ch' in render)

    def test_page_id_in_template(self):
        """Get a page in the templates via the page id."""
        page = self.create_new_page()
        from pages.utils import get_request_mock
        request = get_request_mock()
        temp = loader.get_template('pages/tests/test4.html')
        render = temp.render(RequestContext(request, {}))
        self.assertTrue(page.title() in render)

    def test_bug_178(self):
        """http://code.google.com/p/django-page-cms/issues/detail?id=178"""
        from pages.utils import get_request_mock
        request = get_request_mock()
        temp = loader.get_template('pages/tests/test5.html')
        render = temp.render(RequestContext(request, {'page':None}))

    def test_language_fallback_bug(self):
        """Language fallback doesn't work properly."""
        page = self.create_new_page()

        c = Content(page=page, type='new_type', body='toto', language='en-us')
        c.save()

        self.assertEqual(
            Content.objects.get_content(page, 'en-us', 'new_type'),
            'toto'
        )
        self.assertEqual(
            Content.objects.get_content(page, 'fr-ch', 'new_type'),
            ''
        )
        self.assertEqual(
            Content.objects.get_content(page, 'fr-ch', 'new_type', True),
            'toto'
        )

    def test_bug_156(self):
        c = self.get_admin_client()
        c.login(username= 'batiste', password='b')
        page_data = self.get_new_page_data()
        page_data['slug'] = 'page1'
        page_data['title'] = 'title &'
        response = c.post('/admin/pages/page/add/', page_data)
        page1 = Content.objects.get_content_slug_by_slug('page1').page
        page1.invalidate()
        c = Content.objects.get_content(page1, 'en-us', 'title')
        self.assertEqual(c, page_data['title'])

    def test_bug_181(self):
        c = self.get_admin_client()
        c.login(username= 'batiste', password='b')
        page_data = self.get_new_page_data(draft=True)
        page_data['slug'] = 'page1'

        # create a draft page and ensure we can view it
        response = c.post('/admin/pages/page/add/', page_data)
        response = c.get(self.get_page_url('page1/'))
        self.assertEqual(response.status_code, 200)

        # logout and we should get a 404
        c.logout()
        def func():
            return c.get(self.get_page_url('page1/'))
        self.assert404(func)

        # login as a non staff user and we should get a 404
        c.login(username= 'nonstaff', password='b')
        def func():
            return c.get(self.get_page_url('page1/'))
        self.assert404(func)

    def test_urls_in_templates(self):
        """Test different ways of displaying urls in templates."""
        page = self.create_new_page()
        from pages.phttp import get_request_mock
        request = get_request_mock()
        temp = loader.get_template('pages/tests/test7.html')
        temp = loader.get_template('pages/tests/test6.html')
        render = temp.render(RequestContext(request, {'current_page':page}))

        self.assertTrue('t1_'+page.get_url_path() in render)
        self.assertTrue('t2_'+page.get_url_path() in render)
        self.assertTrue('t3_'+page.get_url_path() in render)
        self.assertTrue('t4_'+page.slug() in render)
        self.assertTrue('t5_'+page.slug() in render)

    def test_placeholder_cache_bug(self):
        """There was an bad bug caused when the page cache was filled
        the first time."""
        from pages.placeholders import PlaceholderNode
        page = self.new_page()
        placeholder = PlaceholderNode('test', page=page)
        placeholder.save(page, 'fr-ch', 'fr', True)
        placeholder.save(page, 'en-us', 'en', True)
        self.assertEqual(
            Content.objects.get_content(page, 'fr-ch', 'test'),
            'fr'
        )

    def test_pages_dynamic_tree_menu_bug(self):
        """
        Test a bug with the dynamic tree template tag doesn't occur anymore.
        http://code.google.com/p/django-page-cms/issues/detail?id=209
        """
        page = self.new_page()
        context = Context({'current_page': page, 'lang':'en-us'})

        pl1 = """{% load pages_tags %}{% pages_dynamic_tree_menu "wrong-slug" %}"""
        template = loader.get_template_from_string(pl1)
        self.assertEqual(template.render(context), '\n')

    def test_placeholder_bug(self):
        """Test placeholder with django template inheritance works prepoerly.
        http://code.google.com/p/django-page-cms/issues/detail?id=210
        """
        p1 = self.new_page(content={'slug':'test', 'one':'one', 'two': 'two'})
        template = django.template.loader.get_template('pages/tests/extends.html')
        context = Context({'current_page': p1, 'lang':'en-us'})
        renderer = template.render(context)
        self.assertTrue('one' in renderer)
        self.assertTrue('two' in renderer)

        from pages.utils import get_placeholders
        self.assertEqual(
            str(get_placeholders('pages/tests/extends.html')),
            '[<Placeholder Node: one>, <Placeholder Node: two>]')

    def test_sanitize(self):
        """Sanitize is broken"""
        <commit_msg>Add the failing test for the broken sanitize<commit_after># -*- coding: utf-8 -*-
"""Django page CMS test suite module"""
from django.template import Template, RequestContext, Context
from django.template import RequestContext, TemplateDoesNotExist
from django.template import loader
import django

from pages.models import Page, Content
from pages.tests.testcase import TestCase

class RegressionTestCase(TestCase):
    """Django page CMS test suite class"""

    def test_calculated_status_bug(self):
        """
        Test the issue 100
        http://code.google.com/p/django-page-cms/issues/detail?id=100
        """
        self.set_setting("PAGE_SHOW_START_DATE", True)
        c = self.get_admin_client()
        c.login(username= 'batiste', password='b')
        page_data = self.get_new_page_data()
        page_data['slug'] = 'page1'
        # create a page for the example otherwise you will get a Http404 error
        response = c.post('/admin/pages/page/add/', page_data)
        page1 = Content.objects.get_content_slug_by_slug('page1').page

        page1.status = Page.DRAFT
        page1.save()

        self.assertEqual(page1.calculated_status, Page.DRAFT)

    def test_slug_bug(self):
        """
        Test the issue 97
        http://code.google.com/p/django-page-cms/issues/detail?id=97
        """
        c = self.get_admin_client()
        c.login(username= 'batiste', password='b')
        page_data = self.get_new_page_data()
        page_data['slug'] = 'page1'
        # create a page for the example otherwise you will get a Http404 error
        response = c.post('/admin/pages/page/add/', page_data)

        response = c.get('/pages/page1/')
        self.assertEqual(response.status_code, 200)

        try:
            response = c.get(self.get_page_url('toto/page1/'))
        except TemplateDoesNotExist as e:
            if e.args != ('404.html',):
                raise

    def test_bug_152(self):
        """Test bug 152
        http://code.google.com/p/django-page-cms/issues/detail?id=152"""
        from pages.utils import get_placeholders
        self.assertEqual(
            str(get_placeholders('pages/tests/test1.html')),
            "[<Placeholder Node: body>]"
        )

    def test_bug_162(self):
        """Test bug 162
        http://code.google.com/p/django-page-cms/issues/detail?id=162"""
        c = self.get_admin_client()
        c.login(username= 'batiste', password='b')
        page_data = self.get_new_page_data()
        page_data['title'] = 'test-162-title'
        page_data['slug'] = 'test-162-slug'
        response = c.post('/admin/pages/page/add/', page_data)
        self.assertRedirects(response, '/admin/pages/page/')
        from pages.utils import get_request_mock
        request = get_request_mock()
        temp = loader.get_template('pages/tests/test2.html')
        render = temp.render(RequestContext(request, {}))
        self.assertTrue('test-162-slug' in render)

    def test_bug_172(self):
        """Test bug 167
        http://code.google.com/p/django-page-cms/issues/detail?id=172"""
        c = self.get_admin_client()
        c.login(username= 'batiste', password='b')
        page_data = self.get_new_page_data()
        page_data['title'] = 'title-en-us'
        page_data['slug'] = 'slug'
        response = c.post('/admin/pages/page/add/', page_data)
        page = Content.objects.get_content_slug_by_slug('slug').page
        Content(page=page, type='title', language='fr-ch',
            body="title-fr-ch").save()

        from pages.utils import get_request_mock
        request = get_request_mock()
        temp = loader.get_template('pages/tests/test3.html')
        render = temp.render(RequestContext(request, {'page':page}))
        self.assertTrue('title-en-us' in render)

        render = temp.render(RequestContext(
            request,
            {'page':page, 'lang':'fr-ch'}
        ))
        self.assertTrue('title-fr-ch' in render)

    def test_page_id_in_template(self):
        """Get a page in the templates via the page id."""
        page = self.create_new_page()
        from pages.utils import get_request_mock
        request = get_request_mock()
        temp = loader.get_template('pages/tests/test4.html')
        render = temp.render(RequestContext(request, {}))
        self.assertTrue(page.title() in render)

    def test_bug_178(self):
        """http://code.google.com/p/django-page-cms/issues/detail?id=178"""
        from pages.utils import get_request_mock
        request = get_request_mock()
        temp = loader.get_template('pages/tests/test5.html')
        render = temp.render(RequestContext(request, {'page':None}))

    def test_language_fallback_bug(self):
        """Language fallback doesn't work properly."""
        page = self.create_new_page()

        c = Content(page=page, type='new_type', body='toto', language='en-us')
        c.save()

        self.assertEqual(
            Content.objects.get_content(page, 'en-us', 'new_type'),
            'toto'
        )
        self.assertEqual(
            Content.objects.get_content(page, 'fr-ch', 'new_type'),
            ''
        )
        self.assertEqual(
            Content.objects.get_content(page, 'fr-ch', 'new_type', True),
            'toto'
        )

    def test_bug_156(self):
        c = self.get_admin_client()
        c.login(username= 'batiste', password='b')
        page_data = self.get_new_page_data()
        page_data['slug'] = 'page1'
        page_data['title'] = 'title &'
        response = c.post('/admin/pages/page/add/', page_data)
        page1 = Content.objects.get_content_slug_by_slug('page1').page
        page1.invalidate()
        c = Content.objects.get_content(page1, 'en-us', 'title')
        self.assertEqual(c, page_data['title'])

    def test_bug_181(self):
        c = self.get_admin_client()
        c.login(username= 'batiste', password='b')
        page_data = self.get_new_page_data(draft=True)
        page_data['slug'] = 'page1'

        # create a draft page and ensure we can view it
        response = c.post('/admin/pages/page/add/', page_data)
        response = c.get(self.get_page_url('page1/'))
        self.assertEqual(response.status_code, 200)

        # logout and we should get a 404
        c.logout()
        def func():
            return c.get(self.get_page_url('page1/'))
        self.assert404(func)

        # login as a non staff user and we should get a 404
        c.login(username= 'nonstaff', password='b')
        def func():
            return c.get(self.get_page_url('page1/'))
        self.assert404(func)

    def test_urls_in_templates(self):
        """Test different ways of displaying urls in templates."""
        page = self.create_new_page()
        from pages.phttp import get_request_mock
        request = get_request_mock()
        temp = loader.get_template('pages/tests/test7.html')
        temp = loader.get_template('pages/tests/test6.html')
        render = temp.render(RequestContext(request, {'current_page':page}))

        self.assertTrue('t1_'+page.get_url_path() in render)
        self.assertTrue('t2_'+page.get_url_path() in render)
        self.assertTrue('t3_'+page.get_url_path() in render)
        self.assertTrue('t4_'+page.slug() in render)
        self.assertTrue('t5_'+page.slug() in render)

    def test_placeholder_cache_bug(self):
        """There was an bad bug caused when the page cache was filled
        the first time."""
        from pages.placeholders import PlaceholderNode
        page = self.new_page()
        placeholder = PlaceholderNode('test', page=page)
        placeholder.save(page, 'fr-ch', 'fr', True)
        placeholder.save(page, 'en-us', 'en', True)
        self.assertEqual(
            Content.objects.get_content(page, 'fr-ch', 'test'),
            'fr'
        )

    def test_pages_dynamic_tree_menu_bug(self):
        """
        Test a bug with the dynamic tree template tag doesn't occur anymore.
        http://code.google.com/p/django-page-cms/issues/detail?id=209
        """
        page = self.new_page()
        context = Context({'current_page': page, 'lang':'en-us'})

        pl1 = """{% load pages_tags %}{% pages_dynamic_tree_menu "wrong-slug" %}"""
        template = loader.get_template_from_string(pl1)
        self.assertEqual(template.render(context), '\n')

    def test_placeholder_bug(self):
        """Test placeholder with django template inheritance works prepoerly.
        http://code.google.com/p/django-page-cms/issues/detail?id=210
        """
        p1 = self.new_page(content={'slug':'test', 'one':'one', 'two': 'two'})
        template = django.template.loader.get_template('pages/tests/extends.html')
        context = Context({'current_page': p1, 'lang':'en-us'})
        renderer = template.render(context)
        self.assertTrue('one' in renderer)
        self.assertTrue('two' in renderer)

        from pages.utils import get_placeholders
        self.assertEqual(
            str(get_placeholders('pages/tests/extends.html')),
            '[<Placeholder Node: one>, <Placeholder Node: two>]')

    def test_sanitize(self):
        """Check that sanitize method is working"""
        self.assertTrue('<script>' not in Content.objects.sanitize("<script>"))<|endoftext|>


<commit_before>import pytest
import logging
import time, datetime
from thespian.test import *
from thespian.actors import *
from datetime import timedelta

MAX_ASK_DELAY = timedelta(seconds=3)

class Message1(object):
    def __init__(self):
        self.m1 = "m1"

class Message2(Message1):
    def __init__(self):
        super(Message2, self).__init__()
        self.m2 = "m2"

class Message3(object): pass
class Message4(object): pass

class StrangeMessage1(Message3): pass
class StrangeMessage2(object): pass

class Bottom(ActorTypeDispatcher):
    def receiveMsg_str(self, msg, sender):
        self.send(sender, "got a string")

    def receiveMsg_Message1(self, msg, sender):
        self.send(sender, "got " + msg.m1)

class Middle(Bottom):
    def receiveMsg_Message2(self, msg, sender):
        self.send(sender, "middle got " + msg.m2)
        return self.SUPER

    def receiveMsg_Message3(self, msg, sender):
        self.send(sender, "middle got #3")

    def receiveUnrecognizedMessage(self, msg, sender):
        self.send(sender, "didn't recognize: %s"%str(type(msg)))

class Top(Middle):
    def receiveMsg_Message3(self, msg, sender):
        self.send(sender, "top got msg3")
        return self.SUPER

    def receiveMsg_Message2(self, msg, sender):
        self.send(sender, "top got " + msg.m2)

    def receiveMsg_str(self, msg, sender):
        self.send(sender, 'top got "'+msg+'"')

    def receiveMsg_int(self, msg, sender):
        self.send(sender, msg * 2)

@pytest.fixture
def bmt_actors(request, asys):
    bottom = asys.createActor(Bottom)
    middle = asys.createActor(Middle)
    top    = asys.createActor(Top)
    return asys, bottom, middle, top

@pytest.fixture
def bottom(request, asys):
    return asys.createActor(Bottom)

@pytest.fixture
def middle(request, asys):
    return asys.createActor(Middle)

@pytest.fixture
def top(request, asys):
    return asys.createActor(Top)

class TestFuncTypeDispatching(object):

    def verifyExpectedResponses(self, asys, target, requestMsg, expected):
        resp = asys.ask(target, requestMsg, MAX_ASK_DELAY)
        if expected == None:
            assert resp is None
        else:
            while resp and expected:
                assert resp in expected
                del expected[expected.index(resp)]
                resp = asys.listen(0.1)
            assert len(expected) == 0

    # --- Bottom --------------------------------------------------

    def testBottomString(self, asys, bottom):
        self.verifyExpectedResponses(asys, bottom, "Are you there?",
                                     ["got a string"])

    def testBottomInt(self, asys, bottom):
        self.verifyExpectedResponses(asys, bottom, 9, None)

    def testBottomMsg1(self, asys, bottom):
        self.verifyExpectedResponses(asys, bottom, Message1(), ["got m1"])

    def testBottomMsg2(self, asys, bottom):
        self.verifyExpectedResponses(asys, bottom, Message2(), ["got m1"])

    def testBottomMsg3(self, asys, bottom):
        self.verifyExpectedResponses(asys, bottom, Message3(), None)

    # --- Middle --------------------------------------------------

    def testMiddleString(self, asys, middle):
        self.verifyExpectedResponses(asys, middle, "Are you there?",
                                     ["got a string"])

    def testMiddleInt(self, asys, middle):
        import sys
        tname = 'class' if sys.version_info >= (3,0,0) else 'type'
        self.verifyExpectedResponses(asys, middle, 9, ["didn't recognize: <%s 'int'>"%tname])

    def testMiddleMsg1(self, asys, middle):
        self.verifyExpectedResponses(asys, middle, Message1(), ["got m1"])

    def testMiddleMsg2(self, asys, middle):
        expected = ["middle got m2", "got m1"]
        resp = asys.ask(middle, Message2(), MAX_ASK_DELAY)
        while resp:
            assert resp in expected
            del expected[expected.index(resp)]
            resp = asys.listen(MAX_ASK_DELAY)
        assert len(expected) == 0

    def testMiddleMsg3(self, asys, middle):
        self.verifyExpectedResponses(asys, middle, Message3(), ["middle got #3"])

    # --- Top --------------------------------------------------

    def testTopString(self, asys, top):
        self.verifyExpectedResponses(asys, top, "Are you there?",
                                     ['top got "Are you there?"'])

    def testTopInt(self, asys, top):
        self.verifyExpectedResponses(asys, top, 9, [18])

    def testTopMsg1(self, asys, top):
        self.verifyExpectedResponses(asys, top, Message1(), ["got m1"])

    def testTopMsg2(self, asys, top):
        expected = ["top got m2"]
        resp = asys.ask(top, Message2(), MAX_ASK_DELAY)
        print('resp',resp)
        while resp:
            assert resp in expected
            del expected[expected.index(resp)]
            resp = asys.listen(MAX_ASK_DELAY)
            print('resp',resp)
        assert len(expected) == 0

    def testTopMsg3(self, asys, top):
        self.verifyExpectedResponses(asys, top, Message3(), ["top got msg3",
                                                            "middle got #3"])

    # --- Unrecognized fallbacks --------------------------------

    def testBottomStrangeSubclass(self, asys, bottom):
        self.verifyExpectedResponses(asys, bottom, StrangeMessage1(), None)

    def testBottomUnrecognized(self, asys, bottom):
        self.verifyExpectedResponses(asys, bottom, StrangeMessage2(), None)

    def testMiddleStrangeSubclass(self, asys, middle):
        self.verifyExpectedResponses(asys, middle, StrangeMessage1(), ["middle got #3"])

    def testMiddleUnrecognized(self, asys, middle):
        self.verifyExpectedResponses(asys, middle, StrangeMessage2(), ["didn't recognize: <class 'thespian.test.test_typeDispatcher.StrangeMessage2'>"])

    def testTopStrangeSubclass(self, asys, top):
        self.verifyExpectedResponses(asys, top, StrangeMessage1(),
                                     ["top got msg3",
                                      "middle got #3"])

    def testTopUnrecognized(self, asys, top):
        self.verifyExpectedResponses(asys, top, StrangeMessage2(),
                                     ["didn't recognize: <class "
                                      "'thespian.test.test_typeDispatcher.StrangeMessage2'>"])

<commit_msg>Update type dispatching test for python 3.6 repr inclusion of address location.<commit_after>import pytest
import logging
import time, datetime
import re
from thespian.test import *
from thespian.actors import *
from thespian.system.utilis import fmap
from datetime import timedelta

MAX_ASK_DELAY = timedelta(seconds=3)

class Message1(object):
    def __init__(self):
        self.m1 = "m1"

class Message2(Message1):
    def __init__(self):
        super(Message2, self).__init__()
        self.m2 = "m2"

class Message3(object): pass
class Message4(object): pass

class StrangeMessage1(Message3): pass
class StrangeMessage2(object): pass

class Bottom(ActorTypeDispatcher):
    def receiveMsg_str(self, msg, sender):
        self.send(sender, "got a string")

    def receiveMsg_Message1(self, msg, sender):
        self.send(sender, "got " + msg.m1)

class Middle(Bottom):
    def receiveMsg_Message2(self, msg, sender):
        self.send(sender, "middle got " + msg.m2)
        return self.SUPER

    def receiveMsg_Message3(self, msg, sender):
        self.send(sender, "middle got #3")

    def receiveUnrecognizedMessage(self, msg, sender):
        self.send(sender, "didn't recognize: %s"%str(type(msg)))

class Top(Middle):
    def receiveMsg_Message3(self, msg, sender):
        self.send(sender, "top got msg3")
        return self.SUPER

    def receiveMsg_Message2(self, msg, sender):
        self.send(sender, "top got " + msg.m2)

    def receiveMsg_str(self, msg, sender):
        self.send(sender, 'top got "'+msg+'"')

    def receiveMsg_int(self, msg, sender):
        self.send(sender, msg * 2)

@pytest.fixture
def bmt_actors(request, asys):
    bottom = asys.createActor(Bottom)
    middle = asys.createActor(Middle)
    top    = asys.createActor(Top)
    return asys, bottom, middle, top

@pytest.fixture
def bottom(request, asys):
    return asys.createActor(Bottom)

@pytest.fixture
def middle(request, asys):
    return asys.createActor(Middle)

@pytest.fixture
def top(request, asys):
    return asys.createActor(Top)

class TestFuncTypeDispatching(object):

    def verifyExpectedResponses(self, asys, target, requestMsg, expected):
        resp = asys.ask(target, requestMsg, MAX_ASK_DELAY)
        if expected == None:
            assert resp is None
        else:
            while resp and expected:
                for n,e in enumerate(expected):
                    if hasattr(e, 'search'):
                        if e.search(resp):
                            break
                    else:
                        if e == resp:
                            break
                else:
                    assert False, 'Expected "%s" not found in: %s'%(
                        resp, fmap(str, expected))
                del expected[n]
                resp = asys.listen(0.1)
            assert len(expected) == 0

    # --- Bottom --------------------------------------------------

    def testBottomString(self, asys, bottom):
        self.verifyExpectedResponses(asys, bottom, "Are you there?",
                                     ["got a string"])

    def testBottomInt(self, asys, bottom):
        self.verifyExpectedResponses(asys, bottom, 9, None)

    def testBottomMsg1(self, asys, bottom):
        self.verifyExpectedResponses(asys, bottom, Message1(), ["got m1"])

    def testBottomMsg2(self, asys, bottom):
        self.verifyExpectedResponses(asys, bottom, Message2(), ["got m1"])

    def testBottomMsg3(self, asys, bottom):
        self.verifyExpectedResponses(asys, bottom, Message3(), None)

    # --- Middle --------------------------------------------------

    def testMiddleString(self, asys, middle):
        self.verifyExpectedResponses(asys, middle, "Are you there?",
                                     ["got a string"])

    def testMiddleInt(self, asys, middle):
        import sys
        tname = 'class' if sys.version_info >= (3,0,0) else 'type'
        self.verifyExpectedResponses(
            asys, middle, 9,
            [re.compile("didn't recognize: <%s 'int'(| at 0x[0-9a-f]+)>"%tname)])

    def testMiddleMsg1(self, asys, middle):
        self.verifyExpectedResponses(asys, middle, Message1(), ["got m1"])

    def testMiddleMsg2(self, asys, middle):
        expected = ["middle got m2", "got m1"]
        resp = asys.ask(middle, Message2(), MAX_ASK_DELAY)
        while resp:
            assert resp in expected
            del expected[expected.index(resp)]
            resp = asys.listen(MAX_ASK_DELAY)
        assert len(expected) == 0

    def testMiddleMsg3(self, asys, middle):
        self.verifyExpectedResponses(asys, middle, Message3(), ["middle got #3"])

    # --- Top --------------------------------------------------

    def testTopString(self, asys, top):
        self.verifyExpectedResponses(asys, top, "Are you there?",
                                     ['top got "Are you there?"'])

    def testTopInt(self, asys, top):
        self.verifyExpectedResponses(asys, top, 9, [18])

    def testTopMsg1(self, asys, top):
        self.verifyExpectedResponses(asys, top, Message1(), ["got m1"])

    def testTopMsg2(self, asys, top):
        expected = ["top got m2"]
        resp = asys.ask(top, Message2(), MAX_ASK_DELAY)
        print('resp',resp)
        while resp:
            assert resp in expected
            del expected[expected.index(resp)]
            resp = asys.listen(MAX_ASK_DELAY)
            print('resp',resp)
        assert len(expected) == 0

    def testTopMsg3(self, asys, top):
        self.verifyExpectedResponses(asys, top, Message3(), ["top got msg3",
                                                            "middle got #3"])

    # --- Unrecognized fallbacks --------------------------------

    def testBottomStrangeSubclass(self, asys, bottom):
        self.verifyExpectedResponses(asys, bottom, StrangeMessage1(), None)

    def testBottomUnrecognized(self, asys, bottom):
        self.verifyExpectedResponses(asys, bottom, StrangeMessage2(), None)

    def testMiddleStrangeSubclass(self, asys, middle):
        self.verifyExpectedResponses(asys, middle,
                                     StrangeMessage1(), ["middle got #3"])

    def testMiddleUnrecognized(self, asys, middle):
        self.verifyExpectedResponses(
            asys, middle, StrangeMessage2(),
            [re.compile("didn't recognize: <class "
                        "'thespian.test.test_typeDispatcher.StrangeMessage2'"
                        "(| at 0x[0-9a-f]+)>")])

    def testTopStrangeSubclass(self, asys, top):
        self.verifyExpectedResponses(asys, top, StrangeMessage1(),
                                     ["top got msg3",
                                      "middle got #3"])

    def testTopUnrecognized(self, asys, top):
        self.verifyExpectedResponses(
            asys, top, StrangeMessage2(),
            [re.compile("didn't recognize: <class "
                        "'thespian.test.test_typeDispatcher.StrangeMessage2'"
                        "(| at 0x[0-9a-f]+)>")])

<|endoftext|>