diff --git a/.pylintrc b/.pylintrc index b674b52..b6bd971 100644 --- a/.pylintrc +++ b/.pylintrc @@ -36,6 +36,7 @@ load-plugins=pylint.extensions.bad_builtin, # no Warning level messages displayed, use"--disable=all --enable=classes # --disable=W" disable=abstract-method, + arguments-differ, bad-builtin, cyclic-import, duplicate-code, @@ -45,6 +46,7 @@ disable=abstract-method, too-many-ancestors, too-many-branches, too-many-instance-attributes, + too-many-lines, too-many-locals, too-many-public-methods, too-many-statements, diff --git a/README.rst b/README.rst index c00f35f..1ba88bf 100644 --- a/README.rst +++ b/README.rst @@ -168,8 +168,9 @@ Launch some specific test. $ python -m unittest tests.test_stranger.TestStranger -If you went into trouble with codestyle (``test_codestyle`` test suite), look at the specific codestyle issues you've got: +Codestyle +^^^^^^^^^ :: - $ pylint randtalkbot setup tests + $ python setup.py lint diff --git a/setup.py b/setup.py index 83249ff..61fc219 100755 --- a/setup.py +++ b/setup.py @@ -4,6 +4,8 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . +import os +import sys from setuptools import setup, Command from setuptools.command.test import test as SetuptoolsTestCommand from randtalkbot.utils import __version__ @@ -27,6 +29,13 @@ def run(self): from coveralls import cli cli.main(self.coveralls_args) +def lint(*options): + from pylint.lint import Run + run = Run(options, exit=False) + + if run.linter.msg_status != os.EX_OK: + sys.exit(run.linter.msg_status) + class LintCommand(Command): user_options = [] @@ -39,8 +48,20 @@ def finalize_options(self): def run(self): self.distribution.fetch_build_eggs(self.distribution.tests_require) - from pylint import epylint as lint - lint.py_run('randtalkbot setup') + lint( + 'randtalkbot', + 'setup', + ) + lint( + '''--disable= + invalid-name, + no-member, + protected-access, + redefined-variable-type, + reimported, + ''', + 'tests', + ) class TestCommand(SetuptoolsTestCommand): def finalize_options(self): @@ -51,7 +72,6 @@ def finalize_options(self): def run_tests(self): import coverage.cmdline - import sys sys.exit(coverage.cmdline.main(argv=['run', '--source=randtalkbot', '-m', 'unittest'])) setup( diff --git a/tests/test_admin_handler.py b/tests/test_admin_handler.py index 934c700..915a810 100644 --- a/tests/test_admin_handler.py +++ b/tests/test_admin_handler.py @@ -4,14 +4,12 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . -import asyncio +from unittest.mock import create_autospec import asynctest from asynctest.mock import call, patch, Mock, CoroutineMock from randtalkbot.admin_handler import AdminHandler -from randtalkbot.stranger_handler import StrangerHandler from randtalkbot.admin_handler import StrangerServiceError from randtalkbot.stranger_setup_wizard import StrangerSetupWizard -from unittest.mock import create_autospec class TestAdminHandler(asynctest.TestCase): @@ -19,14 +17,15 @@ class TestAdminHandler(asynctest.TestCase): @patch('randtalkbot.stranger_handler.StrangerSetupWizard', create_autospec(StrangerSetupWizard)) @patch('randtalkbot.stranger_sender_service.StrangerSenderService._instance') def setUp(self, stranger_sender_service): - from randtalkbot.stranger_handler import StrangerSetupWizard - from randtalkbot.stranger_handler import StrangerService + from randtalkbot.stranger_handler import StrangerSetupWizard as \ + stranger_setup_wizard_cls_mock + from randtalkbot.stranger_handler import StrangerService as stranger_service_cls_mock self.stranger = CoroutineMock() - stranger_service = StrangerService.get_instance.return_value + stranger_service = stranger_service_cls_mock.get_instance.return_value stranger_service.get_or_create_stranger.return_value = self.stranger - StrangerSetupWizard.reset_mock() - self.StrangerSetupWizard = StrangerSetupWizard - self.stranger_setup_wizard = StrangerSetupWizard.return_value + stranger_setup_wizard_cls_mock.reset_mock() + self.stranger_setup_wizard_cls_mock = stranger_setup_wizard_cls_mock + self.stranger_setup_wizard = stranger_setup_wizard_cls_mock.return_value self.stranger_setup_wizard.handle = CoroutineMock() self.initial_msg = { 'from': { @@ -143,7 +142,6 @@ async def test_handle_command_pay__unknown_stranger(self): @patch('randtalkbot.admin_handler.StrangerHandler.handle_command') async def test_handle_command__other_command(self, handle_command): - from randtalkbot.admin_handler import StrangerHandler message = Mock() message.command = 'foo_command' message.command_args = 'foo_args' diff --git a/tests/test_db.py b/tests/test_db.py index 44e3b17..ec4049c 100644 --- a/tests/test_db.py +++ b/tests/test_db.py @@ -5,13 +5,13 @@ # along with this program. If not, see . import unittest -from peewee import * +from unittest.mock import create_autospec, patch, Mock +from peewee import DatabaseError from randtalkbot.db import DB, RetryingDB from randtalkbot.errors import DBError from randtalkbot.stats import Stats from randtalkbot.stranger import Stranger from randtalkbot.talk import Talk -from unittest.mock import create_autospec, patch, Mock class TestDB(unittest.TestCase): @patch('randtalkbot.db.RetryingDB', create_autospec(RetryingDB)) @@ -19,23 +19,23 @@ class TestDB(unittest.TestCase): @patch('randtalkbot.db.stranger') @patch('randtalkbot.db.talk') def setUp(self, stats_module_mock, stranger_module_mock, talk_module_mock): - from randtalkbot.db import RetryingDB + from randtalkbot.db import RetryingDB as retrying_db_cls_mock self.stats_module_mock = stats_module_mock self.stranger_module_mock = stranger_module_mock self.talk_module_mock = talk_module_mock self.database = Mock() - self.RetryingDB = RetryingDB - self.RetryingDB.return_value = self.database + self.retrying_db_cls_mock = retrying_db_cls_mock + self.retrying_db_cls_mock.return_value = self.database self.configuration = Mock() self.configuration.database_host = 'foo_host' self.configuration.database_name = 'foo_name' self.configuration.database_user = 'foo_user' self.configuration.database_password = 'foo_password' - self.RetryingDB.reset_mock() + self.retrying_db_cls_mock.reset_mock() self.db = DB(self.configuration) def test_init__ok(self): - self.RetryingDB.assert_called_once_with( + self.retrying_db_cls_mock.assert_called_once_with( 'foo_name', host='foo_host', user='foo_user', @@ -46,7 +46,7 @@ def test_init__ok(self): self.talk_module_mock.DATABASE_PROXY.initialize.assert_called_once_with(self.database) def test_init__database_troubles(self): - self.RetryingDB.return_value.connect.side_effect = DatabaseError() + self.retrying_db_cls_mock.return_value.connect.side_effect = DatabaseError() with self.assertRaises(DBError): DB(self.configuration) diff --git a/tests/test_i18n.py b/tests/test_i18n.py index 3c2ee2d..9def7ff 100644 --- a/tests/test_i18n.py +++ b/tests/test_i18n.py @@ -5,9 +5,9 @@ # along with this program. If not, see . import unittest +from unittest.mock import call, patch from randtalkbot.i18n import get_languages_names, get_languages_codes, get_translation, \ LanguageNotFoundError -from unittest.mock import call, patch, Mock class TestI18n(unittest.TestCase): def test_get_languages_names__supported(self): diff --git a/tests/test_message.py b/tests/test_message.py index 42b320f..12044af 100644 --- a/tests/test_message.py +++ b/tests/test_message.py @@ -5,8 +5,8 @@ # along with this program. If not, see . import unittest +from unittest.mock import patch, Mock from randtalkbot.message import Message, UnsupportedContentError -from unittest.mock import create_autospec, patch, Mock class TestMessage(unittest.TestCase): def setUp(self): diff --git a/tests/test_stats.py b/tests/test_stats.py index 99f5551..f384b05 100644 --- a/tests/test_stats.py +++ b/tests/test_stats.py @@ -5,9 +5,7 @@ # along with this program. If not, see . import unittest -from peewee import * from randtalkbot.stats import Stats -from unittest.mock import create_autospec, patch, Mock class TestStats(unittest.TestCase): def setUp(self): diff --git a/tests/test_stats_service.py b/tests/test_stats_service.py index 10c42d3..275e83b 100644 --- a/tests/test_stats_service.py +++ b/tests/test_stats_service.py @@ -4,18 +4,17 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . -import asyncio -import asynctest import datetime import json import types -import unittest +import asynctest from asynctest.mock import patch, Mock, CoroutineMock -from peewee import * +from peewee import SqliteDatabase from randtalkbot import stats from randtalkbot.stats_service import StatsService from randtalkbot.stats import Stats +# pylint: disable=line-too-long ENDED_TALKS = ( {'begin': 315535576, 'end': 315539910, 'partner2_sent': 195, 'searched_since': 315525609, 'partner1_sent': 110}, {'begin': 315540982, 'end': 315549266, 'partner2_sent': 89, 'searched_since': 315532407, 'partner1_sent': 72}, @@ -376,7 +375,7 @@ def test_init__no_stats_in_db(self): @asynctest.ignore_loop def test_init__some_stats_in_db_1(self): - stats1 = Stats.create(data_json='', created=datetime.datetime(1980, 1, 1)) + Stats.create(data_json='', created=datetime.datetime(1980, 1, 1)) stats2 = Stats.create(data_json='', created=datetime.datetime(1990, 1, 1)) stats_service = StatsService() self.assertEqual(stats_service._stats, stats2) @@ -384,7 +383,7 @@ def test_init__some_stats_in_db_1(self): @asynctest.ignore_loop def test_init__some_stats_in_db_2(self): stats1 = Stats.create(data_json='', created=datetime.datetime(1990, 1, 1)) - stats2 = Stats.create(data_json='', created=datetime.datetime(1980, 1, 1)) + Stats.create(data_json='', created=datetime.datetime(1980, 1, 1)) stats_service = StatsService() self.assertEqual(stats_service._stats, stats1) @@ -405,18 +404,18 @@ def test_get_stats(self): @patch('randtalkbot.stats_service.asyncio', CoroutineMock()) @patch('randtalkbot.stats_service.datetime', Mock()) async def test_run__ok(self): - from randtalkbot.stats_service import asyncio + from randtalkbot.stats_service import asyncio as asyncio_mock from randtalkbot.stats_service import datetime as datetime_mock self.stats_service._update_stats.reset_mock() datetime_mock.datetime.utcnow.side_effect = [datetime.datetime(1990, 1, 1, 3), RuntimeError] with self.assertRaises(RuntimeError): await self.stats_service.run() - asyncio.sleep.assert_called_once_with(3600) + asyncio_mock.sleep.assert_called_once_with(3600) self.stats_service._update_stats.assert_called_once_with() @patch('randtalkbot.stats_service.asyncio') @patch('randtalkbot.stats_service.datetime', Mock()) - async def test_run__too_late(self, asyncio): + async def test_run__too_late(self, asyncio_mock): from randtalkbot.stats_service import datetime as datetime_mock self.stats_service._update_stats.reset_mock() datetime_mock.datetime.utcnow.side_effect = [ @@ -425,7 +424,7 @@ async def test_run__too_late(self, asyncio): ] with self.assertRaises(RuntimeError): await self.stats_service.run() - asyncio.sleep.assert_not_called() + asyncio_mock.sleep.assert_not_called() self.stats_service._update_stats.assert_called_once_with() @asynctest.ignore_loop @@ -441,11 +440,13 @@ def test_update_stats__no_stats_in_db(self): Talk.get_ended_talks.return_value = get_talks(ENDED_TALKS) self.stats_service._update_stats = types.MethodType(self.update_stats, self.stats_service) self.stats_service._stats = None + # pylint: disable=not-callable self.stats_service._update_stats() Talk.get_not_ended_talks.assert_called_once_with(after=None) Talk.get_ended_talks.assert_called_once_with(after=None) Talk.delete_old.assert_not_called() actual = json.loads(self.stats_service._stats.data_json) + # pylint: disable=bad-continuation expected = { 'languages_count_distribution': [[1, 88], [2, 13]], 'languages_popularity': [['en', 67], ['it', 34], ['ru', 12]], @@ -511,6 +512,7 @@ def test_update_stats__some_stats_in_db(self): Talk.get_ended_talks.return_value = get_talks(ENDED_TALKS) self.stats_service._update_stats = types.MethodType(self.update_stats, self.stats_service) # self.stats_service._stats is not None now. + # pylint: disable=not-callable self.stats_service._update_stats() Talk.get_not_ended_talks.assert_called_once_with(after=datetime.datetime(1990, 1, 1)) Talk.get_ended_talks.assert_called_once_with(after=datetime.datetime(1990, 1, 1)) @@ -531,6 +533,7 @@ def test_update_stats__no_talks(self): Talk.get_ended_talks.return_value = [] self.stats_service._update_stats = types.MethodType(self.update_stats, self.stats_service) # self.stats_service._stats is not None now. + # pylint: disable=not-callable self.stats_service._update_stats() self.assertEqual( json.loads(self.stats_service._stats.data_json), diff --git a/tests/test_stranger.py b/tests/test_stranger.py index 90d4065..0a8ca36 100644 --- a/tests/test_stranger.py +++ b/tests/test_stranger.py @@ -4,27 +4,25 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . -import asyncio -import asynctest import datetime +from unittest.mock import create_autospec +import asynctest from asynctest.mock import call, patch, Mock, CoroutineMock -from peewee import * -from playhouse.test_utils import test_database +from peewee import SqliteDatabase from randtalkbot import stranger from randtalkbot.errors import MissingPartnerError, StrangerError from randtalkbot.stranger import Stranger from randtalkbot.stranger_sender import StrangerSenderError from randtalkbot.stranger_sender_service import StrangerSenderService from telepot.exception import TelegramError -from unittest.mock import create_autospec -database = SqliteDatabase(':memory:') -stranger.DATABASE_PROXY.initialize(database) +DATABASE = SqliteDatabase(':memory:') +stranger.DATABASE_PROXY.initialize(DATABASE) class TestStranger(asynctest.TestCase): def setUp(self): - database.create_tables([Stranger]) + DATABASE.create_tables([Stranger]) self.stranger = Stranger.create( invitation='foo', telegram_id=31416, @@ -43,12 +41,12 @@ def setUp(self): ) def tearDown(self): - database.drop_tables([Stranger]) + DATABASE.drop_tables([Stranger]) @asynctest.ignore_loop def test_init(self): - stranger = Stranger.get(Stranger.telegram_id == 31416) - self.assertEqual(stranger.looking_for_partner_from, None) + stranger_instance = Stranger.get(Stranger.telegram_id == 31416) + self.assertEqual(stranger_instance.looking_for_partner_from, None) @patch('randtalkbot.stranger.INVITATION_LENGTH', 5) @asynctest.ignore_loop @@ -79,7 +77,7 @@ async def test_add_bonuses__muted(self): @patch('randtalkbot.stranger.asyncio', CoroutineMock()) @patch('randtalkbot.stranger.StatsService') async def test_advertise__people_are_searching_chat_lacks_males(self, stats_service_mock): - from randtalkbot.stranger import asyncio + from randtalkbot.stranger import asyncio as asyncio_mock sender = CoroutineMock() self.stranger.get_sender = Mock(return_value=sender) self.stranger.get_start_args = Mock(return_value='foo_start_args') @@ -87,27 +85,33 @@ async def test_advertise__people_are_searching_chat_lacks_males(self, stats_serv self.stranger.save() self.stranger2.looking_for_partner_from = datetime.datetime.utcnow() self.stranger2.save() - stats_service_mock.get_instance.return_value.get_stats.return_value.get_sex_ratio.return_value = 0.9 + stats_service_mock.get_instance \ + .return_value \ + .get_stats \ + .return_value \ + .get_sex_ratio \ + .return_value = 0.9 await self.stranger._advertise() - asyncio.sleep.assert_called_once_with(30) + asyncio_mock.sleep.assert_called_once_with(30) self.assertEqual( sender.send_notification.call_args_list, [ call( - 'The search is going on. {0} users are looking for partner -- change your ' - 'preferences (languages, partner\'s sex) using /setup command to talk with them.\n' - 'Chat *lacks males!* Send the link to your friends and earn {1} bonuses for every ' - 'invited male and {2} bonus for each female (the more bonuses you have -- the faster ' - 'partner\'s search will be):', + 'The search is going on. {0} users are looking for partner -- change your' + ' preferences (languages, partner\'s sex) using /setup command to talk with' + ' them.\n' + 'Chat *lacks males!* Send the link to your friends and earn {1} bonuses for' + ' every invited male and {2} bonus for each female (the more bonuses you' + ' have -- the faster partner\'s search will be):', 2, 3, 1, disable_notification=True, ), call( - 'Do you want to talk with somebody, practice in foreign languages or you just want ' - 'to have some fun? Rand Talk will help you! It\'s a bot matching you with ' - 'a random stranger of desired sex speaking on your language. {0}', + 'Do you want to talk with somebody, practice in foreign languages or you just' + ' want to have some fun? Rand Talk will help you! It\'s a bot matching you' + ' with a random stranger of desired sex speaking on your language. {0}', 'https://telegram.me/RandTalkBot?start=foo_start_args', disable_notification=True, disable_web_page_preview=True, @@ -118,7 +122,7 @@ async def test_advertise__people_are_searching_chat_lacks_males(self, stats_serv @patch('randtalkbot.stranger.asyncio', CoroutineMock()) @patch('randtalkbot.stranger.StatsService') async def test_advertise__people_are_searching_chat_lacks_females(self, stats_service_mock): - from randtalkbot.stranger import asyncio + from randtalkbot.stranger import asyncio as asyncio_mock sender = CoroutineMock() self.stranger.get_sender = Mock(return_value=sender) self.stranger.get_invitation_link = Mock(return_value='foo_invitation_link') @@ -126,27 +130,33 @@ async def test_advertise__people_are_searching_chat_lacks_females(self, stats_se self.stranger.save() self.stranger2.looking_for_partner_from = datetime.datetime.utcnow() self.stranger2.save() - stats_service_mock.get_instance.return_value.get_stats.return_value.get_sex_ratio.return_value = 1.1 + stats_service_mock.get_instance \ + .return_value \ + .get_stats \ + .return_value \ + .get_sex_ratio \ + .return_value = 1.1 await self.stranger._advertise() - asyncio.sleep.assert_called_once_with(30) + asyncio_mock.sleep.assert_called_once_with(30) self.assertEqual( sender.send_notification.call_args_list, [ call( - 'The search is going on. {0} users are looking for partner -- change your ' - 'preferences (languages, partner\'s sex) using /setup command to talk with them.\n' - 'Chat *lacks females!* Send the link to your friends and earn {1} bonuses for every ' - 'invited female and {2} bonus for each male (the more bonuses you have -- the faster ' - 'partner\'s search will be):', + 'The search is going on. {0} users are looking for partner -- change your' + ' preferences (languages, partner\'s sex) using /setup command to talk with' + ' them.\n' + 'Chat *lacks females!* Send the link to your friends and earn {1} bonuses for' + ' every invited female and {2} bonus for each male (the more bonuses you have' + ' -- the faster partner\'s search will be):', 2, 3, 1, disable_notification=True, ), call( - 'Do you want to talk with somebody, practice in foreign languages or you just want ' - 'to have some fun? Rand Talk will help you! It\'s a bot matching you with ' - 'a random stranger of desired sex speaking on your language. {0}', + 'Do you want to talk with somebody, practice in foreign languages or you just' + ' want to have some fun? Rand Talk will help you! It\'s a bot matching you' + ' with a random stranger of desired sex speaking on your language. {0}', 'foo_invitation_link', disable_notification=True, disable_web_page_preview=True, @@ -167,7 +177,6 @@ async def test_advertise__people_are_not_searching(self): @patch('randtalkbot.stranger.StatsService') @patch('randtalkbot.stranger.LOGGER', Mock()) async def test_advertise__stranger_has_blocked_the_bot(self, stats_service_mock): - from randtalkbot.stranger import asyncio from randtalkbot.stranger import LOGGER self.stranger.get_sender = Mock() self.stranger.get_sender.return_value.send_notification = CoroutineMock( @@ -178,8 +187,13 @@ async def test_advertise__stranger_has_blocked_the_bot(self, stats_service_mock) self.stranger.save() self.stranger2.looking_for_partner_from = datetime.datetime.utcnow() self.stranger2.save() - stats_service_mock.get_instance.return_value.get_stats.return_value.get_sex_ratio.return_value = 1.1 - + stats_service_mock.get_instance \ + .return_value \ + .get_stats \ + .return_value \ + .get_sex_ratio \ + .return_value = 1.1 + await self.stranger._advertise() self.assertTrue(LOGGER.warning.called) @@ -305,11 +319,11 @@ def test_get_partner__ok(self): @asynctest.ignore_loop @patch('randtalkbot.stranger.StrangerSenderService', create_autospec(StrangerSenderService)) def test_get_sender(self): - from randtalkbot.stranger import StrangerSenderService - StrangerSenderService.get_instance.return_value.get_or_create_stranger_sender \ + from randtalkbot.stranger import StrangerSenderService as stranger_sender_service_cls_mock + stranger_sender_service_cls_mock.get_instance.return_value.get_or_create_stranger_sender \ .return_value = 'foo_sender' self.assertEqual(self.stranger.get_sender(), 'foo_sender') - StrangerSenderService.get_instance.return_value.get_or_create_stranger_sender \ + stranger_sender_service_cls_mock.get_instance.return_value.get_or_create_stranger_sender \ .assert_called_once_with(self.stranger) @asynctest.ignore_loop @@ -379,7 +393,11 @@ async def test_kick__telegram_error(self): self.stranger._pay_for_talk.assert_called_once_with() self.assertEqual(self.stranger._partner, None) self.assertEqual(self.stranger._talk, None) - LOGGER.warning.assert_called_once_with('Kick. Can\'t notify stranger %d: %s', self.stranger.id, error) + LOGGER.warning.assert_called_once_with( + 'Kick. Can\'t notify stranger %d: %s', + self.stranger.id, + error, + ) @patch('randtalkbot.stranger.asyncio') async def test_mute_bonuses_notifications(self, asyncio_mock): @@ -389,11 +407,11 @@ async def test_mute_bonuses_notifications(self, asyncio_mock): @patch('randtalkbot.stranger.asyncio', CoroutineMock()) async def test_unmute_bonuses_notifications(self): - from randtalkbot.stranger import asyncio + from randtalkbot.stranger import asyncio as asyncio_mock self.stranger.bonus_count = 1200 self.stranger._notify_about_bonuses = CoroutineMock() await self.stranger._unmute_bonuses_notifications(1000) - asyncio.sleep.assert_called_once_with(3600) + asyncio_mock.sleep.assert_called_once_with(3600) self.stranger._notify_about_bonuses.assert_called_once_with(200) async def test_notify_about_bonuses__zero(self): @@ -408,10 +426,10 @@ async def test_notify_about_bonuses__one(self): self.stranger.bonus_count = 1000 await self.stranger._notify_about_bonuses(1) sender.send_notification.assert_called_once_with( - 'You\'ve received one bonus for inviting a person to the bot. ' - 'Bonuses will help you to find partners quickly. Total bonuses count: {0}. ' - 'Congratulations!\n' - 'To mute this notifications, use /mute\\_bonuses.', + 'You\'ve received one bonus for inviting a person to the bot.' + ' Bonuses will help you to find partners quickly. Total bonuses count: {0}.' + ' Congratulations!\n' + 'To mute this notifications, use /mute\\_bonuses.', 1000, ) @@ -421,10 +439,10 @@ async def test_notify_about_bonuses__many(self): self.stranger.bonus_count = 1000 await self.stranger._notify_about_bonuses(2) sender.send_notification.assert_called_once_with( - 'You\'ve received {0} bonuses for inviting a person to the bot. ' - 'Bonuses will help you to find partners quickly. Total bonuses count: {1}. ' - 'Congratulations!\n' - 'To mute this notifications, use /mute\\_bonuses.', + 'You\'ve received {0} bonuses for inviting a person to the bot.' + ' Bonuses will help you to find partners quickly. Total bonuses count: {1}.' + ' Congratulations!\n' + 'To mute this notifications, use /mute\\_bonuses.', 2, 1000, ) @@ -440,7 +458,6 @@ async def test_notify_about_bonuses__telegram_error(self): LOGGER.info.assert_called_once_with('Can\'t notify stranger %d about bonuses: %s', 1, error) async def test_notify_talk_ended__by_self_no_bonuses(self): - from randtalkbot.stranger import get_languages_names sender = CoroutineMock() sender._ = Mock(side_effect=['Chat was finished.', 'Feel free to /begin a new talk.']) self.stranger.get_sender = Mock(return_value=sender) @@ -458,12 +475,14 @@ async def test_notify_talk_ended__by_self_no_bonuses(self): call('Feel free to /begin a new talk.'), ], ) - sender.send_notification.assert_called_once_with('Chat was finished. Feel free to /begin a new talk.') + sender.send_notification \ + .assert_called_once_with('Chat was finished. Feel free to /begin a new talk.') async def test_notify_talk_ended__not_by_self_no_bonuses(self): - from randtalkbot.stranger import get_languages_names sender = CoroutineMock() - sender._ = Mock(side_effect=['Your partner has left chat.', 'Feel free to /begin a new talk.']) + sender._ = Mock( + side_effect=['Your partner has left chat.', 'Feel free to /begin a new talk.'], + ) self.stranger.get_sender = Mock(return_value=sender) self.stranger.get_partner = Mock(return_value=None) talk = Mock() @@ -484,10 +503,11 @@ async def test_notify_talk_ended__not_by_self_no_bonuses(self): ) async def test_notify_talk_ended__telegram_error(self): - from randtalkbot.stranger import get_languages_names sender = CoroutineMock() sender.send_notification.side_effect = TelegramError({}, '', 0) - sender._ = Mock(side_effect=['Your partner has left chat.', 'Feel free to /begin a new talk.']) + sender._ = Mock( + side_effect=['Your partner has left chat.', 'Feel free to /begin a new talk.'], + ) self.stranger.get_sender = Mock(return_value=sender) self.stranger.get_partner = Mock(return_value=None) talk = Mock() @@ -499,7 +519,6 @@ async def test_notify_talk_ended__telegram_error(self): await self.stranger._notify_talk_ended(by_self=False) async def test_notify_talk_ended__not_by_self_was_used_last_bonus(self): - from randtalkbot.stranger import get_languages_names sender = CoroutineMock() sender._ = Mock( side_effect=[ @@ -525,11 +544,11 @@ async def test_notify_talk_ended__not_by_self_was_used_last_bonus(self): ], ) sender.send_notification.assert_called_once_with( - 'Your partner has left chat. You\'ve used your last bonus. Feel free to /begin a new talk.', + 'Your partner has left chat. You\'ve used your last bonus. Feel free to /begin' + ' a new talk.', ) async def test_notify_talk_ended__not_by_self_was_used_a_bonus(self): - from randtalkbot.stranger import get_languages_names sender = CoroutineMock() sender._ = Mock( side_effect=[ @@ -555,13 +574,12 @@ async def test_notify_talk_ended__not_by_self_was_used_a_bonus(self): ], ) sender.send_notification.assert_called_once_with( - 'Your partner has left chat. You\'ve used one bonus. 999 bonus(es) left. Feel free to /begin ' - 'a new talk.', + 'Your partner has left chat. You\'ve used one bonus. 999 bonus(es) left. Feel free' + ' to /begin a new talk.', ) @patch('randtalkbot.stranger.get_languages_names', Mock()) async def test_notify_partner_found__all_languages_are_common(self): - from randtalkbot.stranger import get_languages_names sender = CoroutineMock() sender.update_translation = Mock() sender._ = Mock(side_effect=['Your partner is here.', 'Have a nice chat!']) @@ -583,7 +601,6 @@ async def test_notify_partner_found__all_languages_are_common(self): @patch('randtalkbot.stranger.get_languages_names', Mock()) async def test_notify_partner_found__had_partner_already_no_bonuses(self): - from randtalkbot.stranger import get_languages_names sender = CoroutineMock() sender.update_translation = Mock() sender._ = Mock(side_effect=['Here\'s another stranger.', 'Have a nice chat!']) @@ -610,10 +627,9 @@ async def test_notify_partner_found__had_partner_already_no_bonuses(self): @patch('randtalkbot.stranger.get_languages_names', Mock()) async def test_notify_partner_found__updates_translation(self): - def update_translation(partner=None): + def update_translation(unused_partner=None): sender._ = new_translation - from randtalkbot.stranger import get_languages_names old_translation = Mock() new_translation = Mock(side_effect=['Use {0} please.', 'Your partner is here.']) sender = CoroutineMock() @@ -640,7 +656,6 @@ def update_translation(partner=None): @patch('randtalkbot.stranger.get_languages_names', Mock()) async def test_notify_partner_found__was_bonus_used(self): - from randtalkbot.stranger import get_languages_names sender = CoroutineMock() sender.update_translation = Mock() sender._ = Mock( @@ -668,12 +683,12 @@ async def test_notify_partner_found__was_bonus_used(self): ], ) sender.send_notification.assert_called_once_with( - 'You\'ve used one bonus with previous partner. 1000 bonus(es) left. Here\'s another stranger.', + 'You\'ve used one bonus with previous partner. 1000 bonus(es) left. Here\'s another' + ' stranger.', ) @patch('randtalkbot.stranger.get_languages_names', Mock()) async def test_notify_partner_found__was_bonus_used_no_bonuses_left(self): - from randtalkbot.stranger import get_languages_names sender = CoroutineMock() sender.update_translation = Mock() sender._ = Mock( @@ -739,7 +754,9 @@ async def test_notify_partner_found__knows_uncommon_languages_several_common(sel from randtalkbot.stranger import get_languages_names sender = CoroutineMock() sender.update_translation = Mock() - sender._ = Mock(side_effect=['You can use the following languages: {0}.', 'Your partner is here.', ]) + sender._ = Mock( + side_effect=['You can use the following languages: {0}.', 'Your partner is here.', ], + ) self.stranger.get_sender = Mock(return_value=sender) self.stranger.languages = '["foo", "bar", "baz", "boo"]' self.stranger.get_partner = Mock(return_value=None) @@ -769,8 +786,8 @@ async def test_notify_partner_found__waiting_several_minutes(self): sender = CoroutineMock() sender._ = Mock(side_effect=[ 'Your partner is here.', - 'Your partner\'s been looking for you for {0} min. Say him \"Hello\" -- ' - 'if he doesn\'t respond to you, launch search again by /begin command.', + 'Your partner\'s been looking for you for {0} min. Say him \"Hello\" --' + ' if he doesn\'t respond to you, launch search again by /begin command.', ]) self.stranger.get_sender = Mock(return_value=sender) from randtalkbot.stranger import datetime as datetime_mock @@ -785,13 +802,16 @@ async def test_notify_partner_found__waiting_several_minutes(self): sender._.call_args_list, [ call('Your partner is here.'), - call('Your partner\'s been looking for you for {0} min. Say him \"Hello\" -- ' - 'if he doesn\'t respond to you, launch search again by /begin command.'), + call( + 'Your partner\'s been looking for you for {0} min. Say him \"Hello\" --' + ' if he doesn\'t respond to you, launch search again by /begin command.', + ), ], ) sender.send_notification.assert_called_once_with( - 'Your partner is here. Your partner\'s been looking for you for 11 min. ' - 'Say him "Hello" -- if he doesn\'t respond to you, launch search again by /begin command.', + 'Your partner is here. Your partner\'s been looking for you for 11 min.' + ' Say him "Hello" -- if he doesn\'t respond to you, launch search again by /begin' + ' command.', ) @patch('randtalkbot.stranger.datetime', Mock()) @@ -799,8 +819,8 @@ async def test_notify_partner_found__waiting_several_hours(self): sender = CoroutineMock() sender._ = Mock(side_effect=[ 'Your partner is here.', - 'Your partner\'s been looking for you for {0} hr. Say him \"Hello\" -- ' - 'if he doesn\'t respond to you, launch search again by /begin command.', + 'Your partner\'s been looking for you for {0} hr. Say him \"Hello\" --' + ' if he doesn\'t respond to you, launch search again by /begin command.', ]) self.stranger.get_sender = Mock(return_value=sender) from randtalkbot.stranger import datetime as datetime_mock @@ -815,13 +835,15 @@ async def test_notify_partner_found__waiting_several_hours(self): sender._.call_args_list, [ call('Your partner is here.'), - call('Your partner\'s been looking for you for {0} hr. Say him \"Hello\" -- ' - 'if he doesn\'t respond to you, launch search again by /begin command.'), + call( + 'Your partner\'s been looking for you for {0} hr. Say him \"Hello\" --' + ' if he doesn\'t respond to you, launch search again by /begin command.'), ], ) sender.send_notification.assert_called_once_with( - 'Your partner is here. Your partner\'s been looking for you for 1 hr. ' - 'Say him "Hello" -- if he doesn\'t respond to you, launch search again by /begin command.', + 'Your partner is here. Your partner\'s been looking for you for 1 hr.' + ' Say him "Hello" -- if he doesn\'t respond to you, launch search again by /begin' + ' command.', ) @patch('randtalkbot.stranger.datetime', Mock()) @@ -876,7 +898,6 @@ async def test_notify_partner_found__waiting_only_a_little_bit(self): @patch('randtalkbot.stranger.get_languages_names', Mock()) async def test_notify_partner_found__telegram_error(self): - from randtalkbot.stranger import get_languages_names sender = CoroutineMock() sender.send_notification.side_effect = TelegramError({}, '', 0) sender.update_translation = Mock() @@ -984,13 +1005,23 @@ def test_prevent_advertising__deferred_is_none(self): @patch('randtalkbot.stranger.StatsService', Mock()) async def test_reward_inviter__chat_lacks_such_user(self): from randtalkbot.stranger import StatsService - StatsService.get_instance.return_value.get_stats.return_value.get_sex_ratio.return_value = 1.1 + StatsService.get_instance \ + .return_value \ + .get_stats \ + .return_value \ + .get_sex_ratio \ + .return_value = 1.1 self.stranger.invited_by = self.stranger2 self.stranger2._add_bonuses = CoroutineMock() self.stranger.save = Mock() self.stranger.sex = 'female' await self.stranger._reward_inviter() - StatsService.get_instance.return_value.get_stats.return_value.get_sex_ratio.assert_called_once_with() + StatsService.get_instance \ + .return_value \ + .get_stats \ + .return_value \ + .get_sex_ratio \ + .assert_called_once_with() self.assertEqual(self.stranger.was_invited_as, 'female') self.stranger.save.assert_called_once_with() self.stranger.invited_by._add_bonuses.assert_called_once_with(3) @@ -998,7 +1029,12 @@ async def test_reward_inviter__chat_lacks_such_user(self): @patch('randtalkbot.stranger.StatsService', Mock()) async def test_reward_inviter__chat_doesnt_lack_such_user(self): from randtalkbot.stranger import StatsService - StatsService.get_instance.return_value.get_stats.return_value.get_sex_ratio.return_value = 1.1 + StatsService.get_instance \ + .return_value \ + .get_stats \ + .return_value \ + .get_sex_ratio \ + .return_value = 1.1 self.stranger.invited_by = self.stranger2 self.stranger2._add_bonuses = CoroutineMock() self.stranger.save = Mock() @@ -1075,7 +1111,6 @@ def test_set_languages__same_empty(self): @asynctest.ignore_loop def test_set_languages__too_much(self): - from randtalkbot.errors import StrangerError self.stranger.languages = None with self.assertRaises(StrangerError): # 7 languages. @@ -1118,7 +1153,7 @@ async def test_set_looking_for_partner__bot_was_blocked(self, datetime_mock): @patch('randtalkbot.stranger.datetime', Mock()) @patch('randtalkbot.talk.Talk', Mock()) async def test_set_partner__chatting_stranger(self): - from randtalkbot.stranger import datetime + from randtalkbot.stranger import datetime as datetime_mock from randtalkbot.talk import Talk self.stranger3.looking_for_partner_from = 'foo_searched_since' self.stranger3.save = Mock() @@ -1128,7 +1163,7 @@ async def test_set_partner__chatting_stranger(self): self.stranger._partner = self.stranger2 talk = Mock() self.stranger._talk = talk - datetime.datetime.utcnow.return_value = 'now' + datetime_mock.datetime.utcnow.return_value = 'now' new_talk = Mock() Talk.create.return_value = new_talk await self.stranger.set_partner(self.stranger3) @@ -1167,7 +1202,7 @@ async def test_set_partner__same(self): @patch('randtalkbot.stranger.datetime', Mock()) @patch('randtalkbot.talk.Talk', Mock()) async def test_set_partner__buggy_chatting_stranger(self): - from randtalkbot.stranger import datetime + from randtalkbot.stranger import datetime as datetime_mock from randtalkbot.talk import Talk self.stranger3.looking_for_partner_from = 'foo_searched_since' self.stranger3.save = Mock() @@ -1176,10 +1211,9 @@ async def test_set_partner__buggy_chatting_stranger(self): self.stranger.get_partner = Mock(return_value=self.stranger2) self.stranger._partner = self.stranger2 self.stranger.looking_for_partner_from = 'bar_searched_since' - self.looking_for_partner_from = None talk = Mock() self.stranger._talk = talk - datetime.datetime.utcnow.return_value = 'now' + datetime_mock.datetime.utcnow.return_value = 'now' new_talk = Mock() Talk.create.return_value = new_talk await self.stranger.set_partner(self.stranger3) @@ -1189,17 +1223,16 @@ async def test_set_partner__buggy_chatting_stranger(self): @patch('randtalkbot.stranger.datetime', Mock()) @patch('randtalkbot.talk.Talk', Mock()) async def test_set_partner__not_chatting_stranger(self): - from randtalkbot.stranger import datetime + from randtalkbot.stranger import datetime as datetime_mock from randtalkbot.talk import Talk self.stranger3.looking_for_partner_from = 'foo_searched_since' self.stranger3.save = Mock() self.stranger.get_partner = Mock(return_value=None) self.stranger._partner = None self.stranger.bonus_count = 1000 - self.looking_for_partner_from = None talk = Mock() self.stranger._talk = talk - datetime.datetime.utcnow.return_value = 'now' + datetime_mock.datetime.utcnow.return_value = 'now' new_talk = Mock() Talk.create.return_value = new_talk await self.stranger.set_partner(self.stranger3) diff --git a/tests/test_stranger_handler.py b/tests/test_stranger_handler.py index 423591b..5f33e9a 100644 --- a/tests/test_stranger_handler.py +++ b/tests/test_stranger_handler.py @@ -4,33 +4,29 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . -import asyncio -import asynctest import datetime +from unittest.mock import create_autospec from asynctest.mock import call, patch, Mock, CoroutineMock -from randtalkbot.errors import MissingCommandError, StrangerError, \ - StrangerServiceError, UnknownCommandError, UnsupportedContentError +import asynctest +from telepot.exception import TelegramError +from randtalkbot.errors import StrangerError, StrangerServiceError, UnknownCommandError, \ + UnsupportedContentError from randtalkbot.message import Message from randtalkbot.stranger_handler import StrangerHandler -from randtalkbot.stranger_sender_service import StrangerSenderService -from randtalkbot.stranger_setup_wizard import StrangerSetupWizard -from telepot.exception import TelegramError -from unittest.mock import create_autospec class TestStrangerHandler(asynctest.TestCase): @patch('randtalkbot.stranger_handler.StrangerSetupWizard') @patch('randtalkbot.stranger_sender_service.StrangerSenderService._instance') @patch('randtalkbot.stranger_handler.StrangerService', Mock()) - def setUp(self, stranger_sender_service, StrangerSetupWizard): - from randtalkbot.stranger_handler import Message + def setUp(self, stranger_sender_service, stranger_setup_wizard_cls_mock): from randtalkbot.stranger_handler import StrangerService self.stranger = CoroutineMock() stranger_service = StrangerService.get_instance.return_value stranger_service.get_or_create_stranger.return_value = self.stranger - StrangerSetupWizard.reset_mock() - self.StrangerSetupWizard = StrangerSetupWizard - self.stranger_setup_wizard = StrangerSetupWizard.return_value + stranger_setup_wizard_cls_mock.reset_mock() + self.StrangerSetupWizard = stranger_setup_wizard_cls_mock + self.stranger_setup_wizard = stranger_setup_wizard_cls_mock.return_value self.stranger_setup_wizard.activate = CoroutineMock() self.stranger_setup_wizard.handle = CoroutineMock() self.stranger_setup_wizard.handle_command = CoroutineMock() @@ -54,9 +50,9 @@ def setUp(self, stranger_sender_service, StrangerSetupWizard): @patch('randtalkbot.stranger_handler.StrangerService', Mock()) @patch('randtalkbot.stranger_handler.StrangerSetupWizard') @asynctest.ignore_loop - def test_init__ok(self, StrangerSetupWizard): + def test_init__ok(self, stranger_setup_wizard_cls_mock): from randtalkbot.stranger_handler import StrangerService - stranger_setup_wizard = StrangerSetupWizard.return_value + stranger_setup_wizard = stranger_setup_wizard_cls_mock.return_value stranger_service = StrangerService.get_instance.return_value stranger_service.get_or_create_stranger.return_value = self.stranger self.stranger_handler = StrangerHandler( @@ -68,7 +64,8 @@ def test_init__ok(self, StrangerSetupWizard): self.assertEqual(self.stranger_handler._stranger, self.stranger) self.assertEqual(self.stranger_handler._stranger_setup_wizard, stranger_setup_wizard) stranger_service.get_or_create_stranger.assert_called_once_with(31416) - self.stranger_sender_service.get_or_create_stranger_sender.assert_called_once_with(self.stranger) + self.stranger_sender_service.get_or_create_stranger_sender \ + .assert_called_once_with(self.stranger) self.StrangerSetupWizard.assert_called_once_with(self.stranger) @patch('randtalkbot.stranger_handler.LOGGER', Mock()) @@ -88,7 +85,8 @@ def test_init__stranger_service_error(self): self.assertEqual(self.stranger_handler._stranger, self.stranger) self.assertEqual(self.stranger_handler._stranger_setup_wizard, self.stranger_setup_wizard) stranger_service.get_or_create_stranger.assert_called_once_with(31416) - self.stranger_sender_service.get_or_create_stranger_sender.assert_called_once_with(self.stranger) + self.stranger_sender_service.get_or_create_stranger_sender \ + .assert_called_once_with(self.stranger) self.StrangerSetupWizard.assert_called_once_with(self.stranger) async def test_handle_command__ok(self): @@ -123,7 +121,6 @@ async def test_handle_command_begin(self): async def test_handle_command_begin__partner_obtaining_error(self): from randtalkbot.stranger_service import PartnerObtainingError from randtalkbot.stranger_handler import StrangerService - partner = CoroutineMock() stranger_service = StrangerService.get_instance.return_value stranger_service.match_partner.side_effect = PartnerObtainingError() message = Mock() @@ -135,9 +132,7 @@ async def test_handle_command_begin__partner_obtaining_error(self): @patch('randtalkbot.stranger_handler.LOGGER', Mock()) async def test_handle_command_begin__stranger_service_error(self): from randtalkbot.stranger_handler import LOGGER - from randtalkbot.stranger_service import StrangerServiceError from randtalkbot.stranger_handler import StrangerService - partner = CoroutineMock() stranger_service = StrangerService.get_instance.return_value error = StrangerServiceError() stranger_service.match_partner = CoroutineMock(side_effect=error) @@ -164,14 +159,15 @@ async def test_handle_command_help(self): message = Mock() await self.stranger_handler._handle_command_help(message) self.sender.send_notification.assert_called_once_with( - '*Help*\n\nUse /begin to start looking for a conversational partner, once you\'re matched ' - 'you can use /end to finish the conversation. To choose your settings, apply /setup.\n\n' - 'If you have any suggestions or require help, please contact @quasiyoke. ' - 'When asking questions, please provide this number: {0}.\n\n' - 'Subscribe to [our news](https://telegram.me/RandTalk). ' - 'You\'re welcome to inspect and improve [Rand Talk v. {1} source code]' - '(https://github.com/quasiyoke/RandTalkBot) or to [give us 5 stars]' - '(https://telegram.me/storebot?start=randtalkbot).', + '*Help*\n\nUse /begin to start looking for a conversational partner, once you\'re' + ' matched you can use /end to finish the conversation. To choose your settings, apply' + ' /setup.\n\n' + 'If you have any suggestions or require help, please contact @quasiyoke.' + ' When asking questions, please provide this number: {0}.\n\n' + 'Subscribe to [our news](https://telegram.me/RandTalk).' + ' You\'re welcome to inspect and improve [Rand Talk v. {1} source code]' + '(https://github.com/quasiyoke/RandTalkBot) or to [give us 5 stars]' + '(https://telegram.me/storebot?start=randtalkbot).', 31416, '0.0.0', disable_web_page_preview=True, @@ -224,7 +220,7 @@ async def test_handle_command__start_has_invitation(self): self.stranger.save.assert_called_once_with() self.sender.send_notification.assert_called_once_with( '*Manual*\n\nUse /begin to start looking for a conversational partner, once ' - 'you\'re matched you can use /end to end the conversation.' + 'you\'re matched you can use /end to end the conversation.' ) @patch('randtalkbot.stranger_handler.StrangerService', Mock()) @@ -243,8 +239,8 @@ async def test_handle_command__start_has_invitation_and_already_invited_by(self) stranger_service.get_stranger_by_invitation.assert_not_called() self.assertEqual(self.stranger.invited_by, invited_by) self.sender.send_notification.assert_called_once_with( - '*Manual*\n\nUse /begin to start looking for a conversational partner, once ' - 'you\'re matched you can use /end to end the conversation.' + '*Manual*\n\nUse /begin to start looking for a conversational partner, once' + ' you\'re matched you can use /end to end the conversation.' ) @patch('randtalkbot.stranger_handler.StrangerService', Mock()) @@ -263,10 +259,14 @@ async def test_handle_command__start_has_invited_himself(self): self.assertEqual( self.sender.send_notification.call_args_list, [ - call('Don\'t try to fool me. Forward message with the link to your friends and ' - 'receive well-earned bonuses that will help you to find partner quickly.'), - call('*Manual*\n\nUse /begin to start looking for a conversational partner, once ' - 'you\'re matched you can use /end to end the conversation.'), + call( + 'Don\'t try to fool me. Forward message with the link to your friends and' + ' receive well-earned bonuses that will help you to find partner quickly.' + ), + call( + '*Manual*\n\nUse /begin to start looking for a conversational partner, once' + ' you\'re matched you can use /end to end the conversation.' + ), ], ) @@ -283,8 +283,8 @@ async def test_handle_command__start_has_invalid_invitation(self): stranger_service.get_stranger_by_invitation.assert_not_called() self.assertEqual(self.stranger.invited_by, None) self.sender.send_notification.assert_called_once_with( - '*Manual*\n\nUse /begin to start looking for a conversational partner, once ' - 'you\'re matched you can use /end to end the conversation.' + '*Manual*\n\nUse /begin to start looking for a conversational partner, once' + ' you\'re matched you can use /end to end the conversation.' ) @patch('randtalkbot.stranger_handler.StrangerService', Mock()) @@ -300,8 +300,8 @@ async def test_handle_command__start_has_invalid_invitation_json_keys(self): stranger_service.get_stranger_by_invitation.assert_not_called() self.assertEqual(self.stranger.invited_by, None) self.sender.send_notification.assert_called_once_with( - '*Manual*\n\nUse /begin to start looking for a conversational partner, once ' - 'you\'re matched you can use /end to end the conversation.' + '*Manual*\n\nUse /begin to start looking for a conversational partner, once' + ' you\'re matched you can use /end to end the conversation.' ) @patch('randtalkbot.stranger_handler.StrangerService', Mock()) @@ -317,8 +317,8 @@ async def test_handle_command__start_has_invalid_invitation_json_type(self): stranger_service.get_stranger_by_invitation.assert_not_called() self.assertEqual(self.stranger.invited_by, None) self.sender.send_notification.assert_called_once_with( - '*Manual*\n\nUse /begin to start looking for a conversational partner, once ' - 'you\'re matched you can use /end to end the conversation.' + '*Manual*\n\nUse /begin to start looking for a conversational partner, once' + ' you\'re matched you can use /end to end the conversation.' ) @patch('randtalkbot.stranger_handler.StrangerService', Mock()) @@ -335,8 +335,8 @@ async def test_handle_command__start_has_invalid_invitation_stranger_service_err stranger_service.get_stranger_by_invitation.assert_called_once_with('foo_invitation') self.assertEqual(self.stranger.invited_by, None) self.sender.send_notification.assert_called_once_with( - '*Manual*\n\nUse /begin to start looking for a conversational partner, once ' - 'you\'re matched you can use /end to end the conversation.' + '*Manual*\n\nUse /begin to start looking for a conversational partner, once' + ' you\'re matched you can use /end to end the conversation.' ) async def test_handle_command__start_no_invitation(self): @@ -347,8 +347,8 @@ async def test_handle_command__start_no_invitation(self): await self.stranger_handler._handle_command_start(message) self.assertEqual(self.stranger.invited_by, None) self.sender.send_notification.assert_called_once_with( - '*Manual*\n\nUse /begin to start looking for a conversational partner, once ' - 'you\'re matched you can use /end to end the conversation.' + '*Manual*\n\nUse /begin to start looking for a conversational partner, once' + ' you\'re matched you can use /end to end the conversation.' ) async def test_handle_command__start_no_invitation_is_in_setup(self): @@ -372,26 +372,26 @@ async def test_on_chat_message__not_private(self): @patch('randtalkbot.stranger_handler.Message', create_autospec(Message)) @patch('randtalkbot.stranger_handler.StrangerHandler.handle_command') async def test_on_chat_message__text(self, handle_command_mock): - from randtalkbot.stranger_handler import Message + from randtalkbot.stranger_handler import Message as message_cls_mock from randtalkbot.stranger_handler import telepot telepot.glance.return_value = 'text', 'private', 31416 self.stranger_setup_wizard.handle.return_value = False message_json = { 'text': 'message_text' } - message = Message.return_value + message = message_cls_mock.return_value message.command = None await self.stranger_handler.on_chat_message(message_json) - self.stranger.send_to_partner.assert_called_once_with(Message.return_value) + self.stranger.send_to_partner.assert_called_once_with(message_cls_mock.return_value) self.stranger_setup_wizard.handle.assert_called_once_with(message) - Message.assert_called_once_with(message_json) + message_cls_mock.assert_called_once_with(message_json) handle_command_mock.assert_not_called() @patch('randtalkbot.stranger_handler.telepot', Mock()) @patch('randtalkbot.stranger_handler.Message', create_autospec(Message)) @patch('randtalkbot.stranger_handler.StrangerHandler.handle_command') async def test_on_chat_message__text_no_partner(self, handle_command_mock): - from randtalkbot.stranger_handler import Message + from randtalkbot.stranger_handler import Message as message_cls_mock from randtalkbot.stranger_handler import telepot from randtalkbot.errors import MissingPartnerError telepot.glance.return_value = 'text', 'private', 31416 @@ -400,51 +400,48 @@ async def test_on_chat_message__text_no_partner(self, handle_command_mock): 'text': 'message_text', } self.stranger.send_to_partner = CoroutineMock(side_effect=MissingPartnerError()) - message = Message.return_value + message = message_cls_mock.return_value message.command = None await self.stranger_handler.on_chat_message(message_json) self.stranger.send_to_partner.assert_called_once_with(message) self.stranger_setup_wizard.handle.assert_called_once_with(message) - Message.assert_called_once_with(message_json) + message_cls_mock.assert_called_once_with(message_json) handle_command_mock.assert_not_called() @patch('randtalkbot.stranger_handler.telepot', Mock()) @patch('randtalkbot.stranger_handler.Message', Mock()) @patch('randtalkbot.stranger_handler.StrangerHandler.handle_command') async def test_on_chat_message__text_stranger_error(self, handle_command_mock): - from randtalkbot.stranger_handler import Message + from randtalkbot.stranger_handler import Message as message_cls_mock from randtalkbot.stranger_handler import telepot - from randtalkbot.stranger_handler import StrangerError telepot.glance.return_value = 'text', 'private', 31416 self.stranger_setup_wizard.handle.return_value = False message_json = { 'text': 'message_text', } - Message.return_value.command = None + message_cls_mock.return_value.command = None self.stranger.send_to_partner = CoroutineMock(side_effect=StrangerError()) await self.stranger_handler.on_chat_message(message_json) - self.stranger.send_to_partner.assert_called_once_with(Message.return_value) + self.stranger.send_to_partner.assert_called_once_with(message_cls_mock.return_value) self.sender.send_notification.assert_called_once_with( 'Messages of this type aren\'t supported.', ) - Message.assert_called_once_with(message_json) + message_cls_mock.assert_called_once_with(message_json) handle_command_mock.assert_not_called() @patch('randtalkbot.stranger_handler.LOGGER', Mock()) @patch('randtalkbot.stranger_handler.telepot', Mock()) @patch('randtalkbot.stranger_handler.Message', Mock()) - @patch('randtalkbot.stranger_handler.StrangerHandler.handle_command') - async def test_on_chat_message__text_stranger_has_blocked_the_bot(self, handle_command_mock): + async def test_on_chat_message__text_stranger_has_blocked_the_bot(self): from randtalkbot.stranger_handler import LOGGER - from randtalkbot.stranger_handler import Message + from randtalkbot.stranger_handler import Message as message_cls_mock from randtalkbot.stranger_handler import telepot - from randtalkbot.stranger_handler import StrangerError telepot.glance.return_value = 'text', 'private', 31416 self.stranger_setup_wizard.handle.return_value = False message_json = { 'text': 'message_text', } - Message.return_value.command = None + message_cls_mock.return_value.command = None partner = Mock() partner.id = 27183 self.stranger.get_partner = Mock(return_value=partner) @@ -464,7 +461,7 @@ async def test_on_chat_message__text_stranger_has_blocked_the_bot(self, handle_c @patch('randtalkbot.stranger_handler.StrangerHandler.handle_command') @patch('randtalkbot.stranger_handler.Message', create_autospec(Message)) async def test_on_chat_message__command(self, handle_command_mock): - from randtalkbot.stranger_handler import Message + from randtalkbot.stranger_handler import Message as message_cls_mock from randtalkbot.stranger_handler import telepot telepot.glance.return_value = 'text', 'private', 31416 message_json = { @@ -472,11 +469,11 @@ async def test_on_chat_message__command(self, handle_command_mock): } message = Mock() message.command = 'foo_command' - Message.return_value = message + message_cls_mock.return_value = message self.stranger_setup_wizard.handle_command.return_value = False await self.stranger_handler.on_chat_message(message_json) self.stranger.send_to_partner.assert_not_called() - Message.assert_called_once_with(message_json) + message_cls_mock.assert_called_once_with(message_json) self.stranger_setup_wizard.handle_command.assert_called_once_with(message) handle_command_mock.assert_called_once_with(message) @@ -484,7 +481,7 @@ async def test_on_chat_message__command(self, handle_command_mock): @patch('randtalkbot.stranger_handler.StrangerHandler.handle_command') @patch('randtalkbot.stranger_handler.Message', create_autospec(Message)) async def test_on_chat_message__command_setup(self, handle_command_mock): - from randtalkbot.stranger_handler import Message + from randtalkbot.stranger_handler import Message as message_cls_mock from randtalkbot.stranger_handler import telepot telepot.glance.return_value = 'text', 'private', 31416 message_json = { @@ -492,25 +489,25 @@ async def test_on_chat_message__command_setup(self, handle_command_mock): } message = Mock() message.command = 'foo_command' - Message.return_value = message + message_cls_mock.return_value = message self.stranger_setup_wizard.handle_command.return_value = True await self.stranger_handler.on_chat_message(message_json) self.stranger.send_to_partner.assert_not_called() - Message.assert_called_once_with(message_json) + message_cls_mock.assert_called_once_with(message_json) handle_command_mock.assert_not_called() @patch('randtalkbot.stranger_handler.telepot', Mock()) @patch('randtalkbot.stranger_handler.Message', create_autospec(Message)) @patch('randtalkbot.stranger_handler.StrangerHandler.handle_command') async def test_on_chat_message__command_unknown(self, handle_command_mock): - from randtalkbot.stranger_handler import Message + from randtalkbot.stranger_handler import Message as message_cls_mock from randtalkbot.stranger_handler import telepot telepot.glance.return_value = 'text', 'private', 31416 self.stranger_setup_wizard.handle.return_value = False message_json = { 'text': 'message_text', } - message = Message.return_value + message = message_cls_mock.return_value message.command = 'foo_command' handle_command_mock.side_effect = UnknownCommandError('foo_command') self.stranger_setup_wizard.handle_command.return_value = False @@ -523,12 +520,11 @@ async def test_on_chat_message__command_unknown(self, handle_command_mock): @patch('randtalkbot.stranger_handler.Message', Mock()) @patch('randtalkbot.stranger_handler.StrangerHandler.handle_command') async def test_on_chat_message__not_supported_by_stranger_content(self, handle_command_mock): - from randtalkbot.stranger_handler import Message + from randtalkbot.stranger_handler import Message as message_cls_mock from randtalkbot.stranger_handler import telepot - from randtalkbot.stranger_handler import StrangerError telepot.glance.return_value = 'unsupported_content', 'private', 31416 message_json = Mock() - message = Message.return_value + message = message_cls_mock.return_value message.command = None self.stranger.send_to_partner = CoroutineMock(side_effect=StrangerError()) self.stranger_setup_wizard.handle.return_value = False @@ -537,19 +533,18 @@ async def test_on_chat_message__not_supported_by_stranger_content(self, handle_c self.sender.send_notification.assert_called_once_with( 'Messages of this type aren\'t supported.', ) - Message.assert_called_once_with(message_json) + message_cls_mock.assert_called_once_with(message_json) handle_command_mock.assert_not_called() @patch('randtalkbot.stranger_handler.telepot', Mock()) @patch('randtalkbot.stranger_handler.Message', Mock(side_effect=UnsupportedContentError)) @patch('randtalkbot.stranger_handler.StrangerHandler.handle_command') async def test_on_chat_message__not_supported_by_message_cls_content(self, handle_command_mock): - from randtalkbot.stranger_handler import Message + from randtalkbot.stranger_handler import Message as message_cls_mock from randtalkbot.stranger_handler import telepot - from randtalkbot.stranger_handler import StrangerError telepot.glance.return_value = 'unsupported_content', 'private', 31416 message_json = Mock() - message = Message.return_value + message = message_cls_mock.return_value message.command = None self.stranger.send_to_partner = CoroutineMock() self.stranger_setup_wizard.handle.return_value = False @@ -558,14 +553,14 @@ async def test_on_chat_message__not_supported_by_message_cls_content(self, handl self.sender.send_notification.assert_called_once_with( 'Messages of this type aren\'t supported.', ) - Message.assert_called_once_with(message_json) + message_cls_mock.assert_called_once_with(message_json) handle_command_mock.assert_not_called() @patch('randtalkbot.stranger_handler.telepot', Mock()) @patch('randtalkbot.stranger_handler.Message', Mock()) @patch('randtalkbot.stranger_handler.StrangerHandler.handle_command') async def test_on_chat_message__setup(self, handle_command_mock): - from randtalkbot.stranger_handler import Message + from randtalkbot.stranger_handler import Message as message_cls_mock from randtalkbot.stranger_handler import telepot telepot.glance.return_value = 'text', 'private', 31416 # This means, message was handled by StrangerSetupWizard. @@ -573,12 +568,12 @@ async def test_on_chat_message__setup(self, handle_command_mock): message_json = { 'text': 'message_text', } - message = Message.return_value + message = message_cls_mock.return_value message.command = None self.stranger_setup_wizard.handle.return_value = True await self.stranger_handler.on_chat_message(message_json) self.stranger_setup_wizard.handle.assert_called_once_with(message) - Message.assert_called_once_with(message_json) + message_cls_mock.assert_called_once_with(message_json) handle_command_mock.assert_not_called() async def test_on_edited_chat_message(self): @@ -601,12 +596,15 @@ async def test_on_inline_query(self): 'type': 'article', 'id': 'invitation_link', 'title': 'Rand Talk Invitation Link', - 'description': 'The more friends\'ll use your link -- the faster the search will be', + 'description': ( + 'The more friends\'ll use your link -- the faster the search' + ' will be' + ), 'thumb_url': 'http://randtalk.ml/static/img/logo-500x500.png', 'message_text': ( - 'Do you want to talk with somebody, practice in foreign languages or you just want ' - 'to have some fun? Rand Talk will help you! It\'s a bot matching you with ' - 'a random stranger of desired sex speaking on your language. {0}', + 'Do you want to talk with somebody, practice in foreign languages or you just' + ' want to have some fun? Rand Talk will help you! It\'s a bot matching you' + ' with a random stranger of desired sex speaking on your language. {0}', self.stranger.get_invitation_link.return_value, ), 'parse_mode': 'Markdown', diff --git a/tests/test_stranger_sender.py b/tests/test_stranger_sender.py index ad3e01a..ee89bc7 100644 --- a/tests/test_stranger_sender.py +++ b/tests/test_stranger_sender.py @@ -4,11 +4,10 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . -import asyncio import asynctest +from asynctest.mock import call, patch, Mock, CoroutineMock from randtalkbot.errors import StrangerSenderError from randtalkbot.stranger_sender import StrangerSender -from asynctest.mock import call, patch, Mock, CoroutineMock class TestStrangerSender(asynctest.TestCase): @patch('randtalkbot.stranger_sender.get_translation', Mock()) @@ -28,7 +27,7 @@ def setUp(self): @asynctest.ignore_loop def test_init(self): self.get_translation.reset_mock() - sender = StrangerSender(Mock(), Mock()) + StrangerSender(Mock(), Mock()) StrangerSender.update_translation.assert_called_once_with() async def test_answer_inline_query(self): @@ -92,8 +91,8 @@ async def test_send_notification__escapes_markdown(self): 'foo\\\\` `bar baz\\\\boo foo``', ) self.sender.sendMessage.assert_called_once_with( - '*Rand Talk:* \\*foo\\* \\_bar\\_ \\[baz](http://boo.com) ' - 'foo\\\\\\` \\`bar baz\\\\boo foo\\`\\`', + '*Rand Talk:* \\*foo\\* \\_bar\\_ \\[baz](http://boo.com)' + ' foo\\\\\\` \\`bar baz\\\\boo foo\\`\\`', disable_notification=None, disable_web_page_preview=None, parse_mode='Markdown', diff --git a/tests/test_stranger_sender_service.py b/tests/test_stranger_sender_service.py index 8082d08..f1f942c 100644 --- a/tests/test_stranger_sender_service.py +++ b/tests/test_stranger_sender_service.py @@ -1,17 +1,16 @@ -# RandTalkBot Bot matching you with a random person on Telegram. + # RandTalkBot Bot matching you with a random person on Telegram. # Copyright (C) 2016 quasiyoke # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . import unittest +from unittest.mock import create_autospec, patch, Mock from randtalkbot.stranger_sender import StrangerSender from randtalkbot.stranger_sender_service import StrangerSenderService, StrangerSenderServiceError -from unittest.mock import call, create_autospec, patch, Mock class TestStrangerSenderService(unittest.TestCase): - @patch('randtalkbot.stranger_sender_service.StrangerSender') - def setUp(self, stranger_sender_cls_mock): + def setUp(self): self.bot = Mock() self.stranger_sender_service = StrangerSenderService(self.bot) # Cached instance should be cleared for each test. @@ -41,7 +40,7 @@ def test_get_cache_size(self): @patch('randtalkbot.stranger_sender_service.StrangerSender', create_autospec(StrangerSender)) def test_get_or_create_stranger_sender__cached(self): - from randtalkbot.stranger_sender_service import StrangerSender + from randtalkbot.stranger_sender_service import StrangerSender as stranger_sender_cls_mock stranger_sender = Mock() stranger = Mock() stranger.telegram_id = 31416 @@ -50,17 +49,17 @@ def test_get_or_create_stranger_sender__cached(self): self.stranger_sender_service.get_or_create_stranger_sender(stranger), stranger_sender, ) - self.assertFalse(StrangerSender.called) + self.assertFalse(stranger_sender_cls_mock.called) @patch('randtalkbot.stranger_sender_service.StrangerSender', create_autospec(StrangerSender)) def test_get_or_create_stranger_sender__not_cached(self): - from randtalkbot.stranger_sender_service import StrangerSender - stranger_sender = StrangerSender.return_value + from randtalkbot.stranger_sender_service import StrangerSender as stranger_sender_cls_mock + stranger_sender = stranger_sender_cls_mock.return_value stranger = Mock() stranger.telegram_id = 31416 self.assertEqual( self.stranger_sender_service.get_or_create_stranger_sender(stranger), stranger_sender, ) - StrangerSender.assert_called_once_with(self.bot, stranger) + stranger_sender_cls_mock.assert_called_once_with(self.bot, stranger) self.assertEqual(self.stranger_sender_service._stranger_senders[31416], stranger_sender) diff --git a/tests/test_stranger_service.py b/tests/test_stranger_service.py index d4c576b..2d85750 100644 --- a/tests/test_stranger_service.py +++ b/tests/test_stranger_service.py @@ -4,18 +4,16 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . -import asynctest import datetime -import unittest +from unittest.mock import create_autospec +import asynctest from asynctest.mock import call, patch, Mock, CoroutineMock -from peewee import * -from playhouse.test_utils import test_database +from peewee import DatabaseError, DoesNotExist, SqliteDatabase from randtalkbot import stranger from randtalkbot.errors import StrangerError, StrangerServiceError, \ PartnerObtainingError from randtalkbot.stranger import Stranger from randtalkbot.stranger_service import StrangerService -from unittest.mock import create_autospec class TestStrangerService(asynctest.TestCase): @@ -95,16 +93,15 @@ def test_get_cached_stranger__cached(self): cached_stranger = Mock() cached_stranger.id = 31416 self.stranger_service._strangers_cache[31416] = cached_stranger - stranger = Mock() stranger.id = 31416 self.assertEqual(self.stranger_service.get_cached_stranger(stranger), cached_stranger) @asynctest.ignore_loop def test_get_cached_stranger__not_cached(self): - stranger = Mock() - stranger.id = 31416 - self.assertEqual(self.stranger_service.get_cached_stranger(stranger), stranger) - self.assertEqual(self.stranger_service._strangers_cache[31416], stranger) + stranger_mock = Mock() + stranger_mock.id = 31416 + self.assertEqual(self.stranger_service.get_cached_stranger(stranger_mock), stranger_mock) + self.assertEqual(self.stranger_service._strangers_cache[31416], stranger_mock) @asynctest.ignore_loop def test_get_cache_size(self): @@ -123,8 +120,8 @@ def test_get_full_strangers(self): @patch('randtalkbot.stranger_service.Stranger', create_autospec(Stranger)) @asynctest.ignore_loop def test_get_or_create_stranger__stranger_found(self): - from randtalkbot.stranger_service import Stranger - Stranger.get.return_value = self.stranger_0 + from randtalkbot.stranger_service import Stranger as stranger_cls_mock + stranger_cls_mock.get.return_value = self.stranger_0 self.stranger_service.get_cached_stranger = Mock() self.stranger_service.get_cached_stranger.return_value = 'cached_stranger' self.assertEqual( @@ -136,9 +133,9 @@ def test_get_or_create_stranger__stranger_found(self): @patch('randtalkbot.stranger_service.Stranger', create_autospec(Stranger)) @asynctest.ignore_loop def test_get_or_create_stranger__stranger_not_found(self): - from randtalkbot.stranger_service import Stranger - Stranger.get.side_effect = DoesNotExist() - Stranger.create.return_value = self.stranger_0 + from randtalkbot.stranger_service import Stranger as stranger_cls_mock + stranger_cls_mock.get.side_effect = DoesNotExist() + stranger_cls_mock.create.return_value = self.stranger_0 self.stranger_service.get_cached_stranger = Mock() self.stranger_service.get_cached_stranger.return_value = 'cached_stranger' self.assertEqual( @@ -150,9 +147,9 @@ def test_get_or_create_stranger__stranger_not_found(self): @patch('randtalkbot.stranger_service.Stranger', create_autospec(Stranger)) @asynctest.ignore_loop def test_get_or_create_stranger__database_error(self): - from randtalkbot.stranger_service import Stranger + from randtalkbot.stranger_service import Stranger as stranger_cls_mock self.stranger_service.get_cached_stranger = Mock() - Stranger.get.side_effect = DatabaseError() + stranger_cls_mock.get.side_effect = DatabaseError() with self.assertRaises(StrangerServiceError): self.stranger_service.get_or_create_stranger(31416) @@ -702,39 +699,39 @@ def test_match_partner__does_not_exist(self): self.stranger_service.get_cached_stranger.assert_not_called() async def test_match_partner__ok(self): - stranger = CoroutineMock() + stranger_mock = CoroutineMock() partner = CoroutineMock() partner.id = 31416 self.stranger_service._match_partner = Mock(return_value=partner) self.stranger_service._locked_strangers_ids = Mock() - await self.stranger_service.match_partner(stranger) + await self.stranger_service.match_partner(stranger_mock) self.stranger_service._locked_strangers_ids.discard. \ assert_called_once_with(31416) - stranger.notify_partner_found.assert_called_once_with(partner) - partner.notify_partner_found.assert_called_once_with(stranger) - stranger.set_partner.assert_called_once_with(partner) + stranger_mock.notify_partner_found.assert_called_once_with(partner) + partner.notify_partner_found.assert_called_once_with(stranger_mock) + stranger_mock.set_partner.assert_called_once_with(partner) async def test_match_partner__stranger_error(self): - stranger = CoroutineMock() + stranger_mock = CoroutineMock() partner = CoroutineMock() partner.id = 31416 self.stranger_service._match_partner = Mock(return_value=partner) self.stranger_service._locked_strangers_ids = Mock() - stranger.notify_partner_found.side_effect = StrangerError() + stranger_mock.notify_partner_found.side_effect = StrangerError() with self.assertRaises(StrangerServiceError): - await self.stranger_service.match_partner(stranger) + await self.stranger_service.match_partner(stranger_mock) self.stranger_service._locked_strangers_ids.discard. \ assert_called_once_with(31416) - stranger.set_partner.assert_not_called() + stranger_mock.set_partner.assert_not_called() async def test_match_partner__first_partner_has_blocked_the_bot(self): - stranger = CoroutineMock() + stranger_mock = CoroutineMock() partner = CoroutineMock() partner.id = 31416 self.stranger_service._match_partner = Mock(return_value=partner) self.stranger_service._locked_strangers_ids = Mock() partner.notify_partner_found.side_effect = [StrangerError(), None] - await self.stranger_service.match_partner(stranger) + await self.stranger_service.match_partner(stranger_mock) self.assertEqual( self.stranger_service._locked_strangers_ids.discard.call_args_list, [ @@ -745,17 +742,16 @@ async def test_match_partner__first_partner_has_blocked_the_bot(self): self.assertEqual( partner.notify_partner_found.call_args_list, [ - call(stranger), - call(stranger), + call(stranger_mock), + call(stranger_mock), ], ) - stranger.notify_partner_found.assert_called_once_with(partner) + stranger_mock.notify_partner_found.assert_called_once_with(partner) async def test_match_partner__partner_obtaining_error(self): - from randtalkbot.stranger_service import PartnerObtainingError - stranger = CoroutineMock() + stranger_mock = CoroutineMock() self.stranger_service._match_partner = Mock( side_effect=PartnerObtainingError, ) with self.assertRaises(PartnerObtainingError): - await self.stranger_service.match_partner(stranger) + await self.stranger_service.match_partner(stranger_mock) diff --git a/tests/test_stranger_setup_wizard.py b/tests/test_stranger_setup_wizard.py index 3b93b73..72fe9b7 100644 --- a/tests/test_stranger_setup_wizard.py +++ b/tests/test_stranger_setup_wizard.py @@ -4,17 +4,12 @@ # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see . -import asyncio import asynctest from asynctest.mock import patch, Mock, CoroutineMock -from randtalkbot.errors import * +from telepot.exception import TelegramError +from randtalkbot.errors import EmptyLanguagesError, SexError from randtalkbot.i18n import LanguageNotFoundError -from randtalkbot.stranger_handler import * -from randtalkbot.stranger_sender_service import * -from randtalkbot.stranger_service import StrangerServiceError from randtalkbot.stranger_setup_wizard import StrangerSetupWizard -from telepot.exception import TelegramError -from unittest.mock import create_autospec class TestStrangerSetupWizard(asynctest.TestCase): @@ -29,7 +24,9 @@ def setUp(self, stranger_sender_service): @asynctest.ignore_loop def test_init(self): - self.stranger_sender_service.get_or_create_stranger_sender.assert_called_once_with(self.stranger) + self.stranger_sender_service \ + .get_or_create_stranger_sender \ + .assert_called_once_with(self.stranger) async def test_activate(self): self.stranger_setup_wizard._prompt = CoroutineMock() @@ -52,10 +49,10 @@ async def test_deactivate(self): @patch('randtalkbot.stranger_setup_wizard.LOGGER', Mock()) async def test_deactivate__telegram_error(self): - from randtalkbot.stranger_setup_wizard import LOGGER + from randtalkbot.stranger_setup_wizard import LOGGER as logger_mock self.sender.send_notification.side_effect = TelegramError({}, '', 0) await self.stranger_setup_wizard.deactivate() - self.assertTrue(LOGGER.warning.called) + self.assertTrue(logger_mock.warning.called) async def test_handle__deactivated_novice(self): self.stranger.wizard = 'none' @@ -103,7 +100,6 @@ async def test_handle__languages_ok(self): @patch('randtalkbot.stranger_setup_wizard.get_languages_codes', Mock()) async def test_handle__languages_empty_languages_error(self): from randtalkbot.stranger_setup_wizard import get_languages_codes - from randtalkbot.errors import EmptyLanguagesError self.stranger.wizard = 'setup' self.stranger.wizard_step = 'languages' get_languages_codes.side_effect = EmptyLanguagesError() @@ -114,7 +110,9 @@ async def test_handle__languages_empty_languages_error(self): get_languages_codes.assert_called_once_with('foo_text') self.stranger.set_languages.assert_not_called() self.stranger_setup_wizard._prompt.assert_called_once_with() - self.sender.send_notification.assert_called_once_with('Please specify at least one language.') + self.sender \ + .send_notification \ + .assert_called_once_with('Please specify at least one language.') @patch('randtalkbot.stranger_setup_wizard.get_languages_codes', Mock()) async def test_handle__languages_language_not_found(self): @@ -138,7 +136,7 @@ async def test_handle__languages_language_not_found(self): @patch('randtalkbot.stranger_setup_wizard.get_languages_codes', Mock()) async def test_handle__languages_too_much(self): from randtalkbot.stranger_setup_wizard import get_languages_codes - from randtalkbot.stranger_setup_wizard import LOGGER + from randtalkbot.stranger_setup_wizard import LOGGER as logger_mock from randtalkbot.errors import StrangerError self.stranger.wizard = 'setup' self.stranger.wizard_step = 'languages' @@ -153,7 +151,8 @@ async def test_handle__languages_too_much(self): self.sender.send_notification.assert_called_once_with( 'Too much languages were specified. Please shorten your list to 6 languages.', ) - LOGGER.info.assert_called_once_with('Too much languages were specified: \"%s\"', 'foo_text') + logger_mock.info \ + .assert_called_once_with('Too much languages were specified: \"%s\"', 'foo_text') async def test_handle__sex_ok(self): self.stranger.wizard = 'setup' @@ -183,7 +182,6 @@ async def test_handle__sex_not_specified(self): self.stranger.save.assert_not_called() async def test_handle__sex_sex_error(self): - from randtalkbot.errors import SexError self.stranger.wizard = 'setup' self.stranger.wizard_step = 'sex' self.stranger_setup_wizard._prompt = CoroutineMock() @@ -214,7 +212,6 @@ async def test_handle__partner_sex_ok(self): self.stranger.save.assert_not_called() async def test_handle__partner_sex_sex_error(self): - from randtalkbot.errors import SexError self.stranger.wizard = 'setup' self.stranger.wizard_step = 'partner_sex' self.stranger_setup_wizard._prompt = CoroutineMock() @@ -231,7 +228,7 @@ async def test_handle__partner_sex_sex_error(self): @patch('randtalkbot.stranger_setup_wizard.LOGGER', Mock()) async def test_handle__unknown_wizard_step(self): - from randtalkbot.stranger_setup_wizard import LOGGER + from randtalkbot.stranger_setup_wizard import LOGGER as logger_mock self.stranger.wizard = 'setup' self.stranger.wizard_step = 'unknown_step' self.stranger_setup_wizard._prompt = CoroutineMock() @@ -240,12 +237,13 @@ async def test_handle__unknown_wizard_step(self): self.assertTrue((await self.stranger_setup_wizard.handle(message))) self.stranger_setup_wizard._prompt.assert_not_called() self.sender.send_notification.assert_not_called() - LOGGER.warning.assert_called_once_with('Undknown wizard_step value was found: "%s"', 'unknown_step') + logger_mock.warning \ + .assert_called_once_with('Undknown wizard_step value was found: "%s"', 'unknown_step') @patch('randtalkbot.stranger_setup_wizard.LOGGER', Mock()) @patch('randtalkbot.stranger_setup_wizard.get_languages_codes', Mock()) async def test_handle__telegram_error(self): - from randtalkbot.stranger_setup_wizard import LOGGER + from randtalkbot.stranger_setup_wizard import LOGGER as logger_mock from randtalkbot.stranger_setup_wizard import get_languages_codes self.stranger.wizard = 'setup' self.stranger.wizard_step = 'languages' @@ -255,7 +253,7 @@ async def test_handle__telegram_error(self): message.text = 'foo_text' self.sender.send_notification.side_effect = TelegramError({}, '', 0) self.assertTrue((await self.stranger_setup_wizard.handle(message))) - self.assertTrue(LOGGER.warning.called) + self.assertTrue(logger_mock.warning.called) async def test_handle_command__not_activated_handled(self): self.stranger.wizard = 'none' @@ -309,7 +307,7 @@ async def test_handle_command__not_full_stranger(self): @patch('randtalkbot.stranger_setup_wizard.LOGGER', Mock()) async def test_handle_command__telegram_error(self): - from randtalkbot.stranger_setup_wizard import LOGGER + from randtalkbot.stranger_setup_wizard import LOGGER as logger_mock self.stranger.wizard = 'setup' self.stranger.wizard_step = 'sex' self.stranger.is_full.return_value = False @@ -318,7 +316,7 @@ async def test_handle_command__telegram_error(self): message.command = 'begin' self.sender.send_notification.side_effect = TelegramError({}, '', 0) self.assertTrue((await self.stranger_setup_wizard.handle_command(message))) - self.assertTrue(LOGGER.warning.called) + self.assertTrue(logger_mock.warning.called) @patch( 'randtalkbot.stranger_setup_wizard.SUPPORTED_LANGUAGES_NAMES', @@ -346,9 +344,9 @@ async def test_prompt__one_language(self): self.stranger.get_languages.return_value = ['pt'] await self.stranger_setup_wizard._prompt() self.sender.send_notification.assert_called_once_with( - 'Your current language is {0}. Enumerate the languages you speak like this: ' - '"English, Italian" -- in descending order of your speaking convenience ' - 'or just pick one at special keyboard.', + 'Your current language is {0}. Enumerate the languages you speak like this:' + ' "English, Italian" -- in descending order of your speaking convenience' + ' or just pick one at special keyboard.', 'Português', reply_markup={ 'keyboard': [ @@ -369,9 +367,9 @@ async def test_prompt__many_language(self): self.stranger.get_languages.return_value = ['pt', 'de', 'en'] await self.stranger_setup_wizard._prompt() self.sender.send_notification.assert_called_once_with( - 'Your current languages are: {0}. Enumerate the languages you speak the same way ' - '-- in descending order of your speaking convenience or just pick one ' - 'at special keyboard.', + 'Your current languages are: {0}. Enumerate the languages you speak the same way' + ' -- in descending order of your speaking convenience or just pick one' + ' at special keyboard.', 'Português, Deutsch, English', reply_markup={ 'keyboard': [ @@ -397,8 +395,8 @@ async def test_prompt__unknown_languages(self): self.stranger.get_languages.return_value = [] await self.stranger_setup_wizard._prompt() self.sender.send_notification.assert_called_once_with( - 'Enumerate the languages you speak like this: "English, Italian" -- in descending ' + \ - 'order of your speaking convenience or just pick one at special keyboard.', + 'Enumerate the languages you speak like this: "English, Italian" -- in descending' + ' order of your speaking convenience or just pick one at special keyboard.', '', reply_markup={'keyboard': [('English', 'Português'), ('Italiano', 'Русский')]}, ) @@ -429,10 +427,10 @@ async def test_prompt__other_step(self): @patch('randtalkbot.stranger_setup_wizard.LOGGER', Mock()) async def test_prompt__telegram_error(self): - from randtalkbot.stranger_setup_wizard import LOGGER + from randtalkbot.stranger_setup_wizard import LOGGER as logger_mock self.stranger.wizard = 'setup' self.stranger.wizard_step = 'languages' self.stranger.get_languages.return_value = [] self.sender.send_notification.side_effect = TelegramError({}, '', 0) await self.stranger_setup_wizard._prompt() - self.assertTrue(LOGGER.warning.called) + self.assertTrue(logger_mock.warning.called) diff --git a/tests/test_talk.py b/tests/test_talk.py index ccea618..cf6e4f9 100644 --- a/tests/test_talk.py +++ b/tests/test_talk.py @@ -6,21 +6,20 @@ import datetime import unittest -from peewee import * -from playhouse.test_utils import test_database +from unittest.mock import patch, Mock +from peewee import SqliteDatabase from randtalkbot import talk, stranger from randtalkbot.errors import WrongStrangerError from randtalkbot.talk import Talk from randtalkbot.stranger import Stranger -from unittest.mock import create_autospec, patch, Mock -database = SqliteDatabase(':memory:') -stranger.DATABASE_PROXY.initialize(database) -talk.DATABASE_PROXY.initialize(database) +DATABASE = SqliteDatabase(':memory:') +stranger.DATABASE_PROXY.initialize(DATABASE) +talk.DATABASE_PROXY.initialize(DATABASE) class TestTalk(unittest.TestCase): def setUp(self): - database.create_tables([Stranger, Talk]) + DATABASE.create_tables([Stranger, Talk]) self.stranger_0 = Stranger.create( invitation='foo', telegram_id=31416, @@ -78,7 +77,7 @@ def setUp(self): ) def tearDown(self): - database.drop_tables([Talk, Stranger]) + DATABASE.drop_tables([Talk, Stranger]) def test_delete_old__0(self): Talk.delete_old(datetime.datetime(2010, 1, 2, 12)) @@ -163,12 +162,13 @@ def test_get_not_ended_talks(self): @patch('randtalkbot.talk.StrangerService', Mock()) def test_get_talk__0(self): from randtalkbot.talk import StrangerService + # pylint: disable=no-member stranger_service = StrangerService.get_instance.return_value stranger_service.get_cached_stranger.side_effect = [self.stranger_2, self.stranger_3, ] - talk = Talk.get_talk(self.stranger_0) - self.assertEqual(talk, self.talk_0) - self.assertEqual(talk.partner1, self.stranger_2) - self.assertEqual(talk.partner2, self.stranger_3) + talk_instance = Talk.get_talk(self.stranger_0) + self.assertEqual(talk_instance, self.talk_0) + self.assertEqual(talk_instance.partner1, self.stranger_2) + self.assertEqual(talk_instance.partner2, self.stranger_3) @patch('randtalkbot.talk.StrangerService', Mock()) def test_get_talk__1(self):