Switch to pytest + required fixes to code (#788)

Required fixes:
 - CallbackQuery is now comparable.
 - Message.effective_attachment, Message.photo,
   Message.new_chat_members, Message.new_chat_photo &
   Game.text_entitties semantic fixes - when they are not defined,
   return an empty list.
 - Docstring fix to Update class.
This commit is contained in:
Jacob Bom 2017-08-11 23:58:41 +02:00 committed by Noam Meltzer
parent 915cd64140
commit 5d7c6ad541
111 changed files with 8370 additions and 7377 deletions

View file

@ -1,8 +0,0 @@
[run]
source = telegram
omit = telegram/vendor/*
[report]
omit =
tests/
telegram/vendor/*

View file

@ -1,10 +1,10 @@
How To Contribute How To Contribute
=================== =================
Every open source project lives from the generous help by contributors that sacrifice their time and ``python-telegram-bot`` is no different. To make participation as pleasant as possible, this project adheres to the `Code of Conduct`_ by the Python Software Foundation. Every open source project lives from the generous help by contributors that sacrifice their time and ``python-telegram-bot`` is no different. To make participation as pleasant as possible, this project adheres to the `Code of Conduct`_ by the Python Software Foundation.
Setting things up Setting things up
------------------- -----------------
1. Fork the ``python-telegram-bot`` repository to your GitHub account. 1. Fork the ``python-telegram-bot`` repository to your GitHub account.
@ -35,7 +35,7 @@ Setting things up
$ pre-commit install $ pre-commit install
Finding something to do Finding something to do
################### #######################
If you already know what you'd like to work on, you can skip this section. If you already know what you'd like to work on, you can skip this section.
@ -44,7 +44,7 @@ If you have an idea for something to do, first check if it's already been filed
Another great way to start contributing is by writing tests. Tests are really important because they help prevent developers from accidentally breaking existing code, allowing them to build cool things faster. If you're interested in helping out, let the development team know by posting to the `developers' mailing list`_, and we'll help you get started. Another great way to start contributing is by writing tests. Tests are really important because they help prevent developers from accidentally breaking existing code, allowing them to build cool things faster. If you're interested in helping out, let the development team know by posting to the `developers' mailing list`_, and we'll help you get started.
Instructions for making a code change Instructions for making a code change
#################### #####################################
The central development branch is ``master``, which should be clean and ready for release at any time. In general, all changes should be done as feature branches based off of ``master``. The central development branch is ``master``, which should be clean and ready for release at any time. In general, all changes should be done as feature branches based off of ``master``.
@ -89,7 +89,7 @@ Here's how to make a one-off code change.
.. code-block:: .. code-block::
$ nosetests -v $ pytest -v
- To actually make the commit (this will trigger tests for yapf, lint and pep8 automatically): - To actually make the commit (this will trigger tests for yapf, lint and pep8 automatically):
@ -155,20 +155,29 @@ Here's how to make a one-off code change.
7. **Celebrate.** Congratulations, you have contributed to ``python-telegram-bot``! 7. **Celebrate.** Congratulations, you have contributed to ``python-telegram-bot``!
Style commandments Style commandments
--------------------- ------------------
Specific commandments Specific commandments
##################### #####################
- Avoid using "double quotes" where you can reasonably use 'single quotes'. - Avoid using "double quotes" where you can reasonably use 'single quotes'.
AssertEqual argument order Assert comparison order
###################### #######################
- assertEqual method's arguments should be in ('actual', 'expected') order. - assert statements should compare in **actual** == **expected** order.
For example (assuming ``test_call`` is the thing being tested):
.. code-block:: python
# GOOD
assert test_call() == 5
# BAD
assert 5 == test_call()
Properly calling callables Properly calling callables
####################### ##########################
Methods, functions and classes can specify optional parameters (with default Methods, functions and classes can specify optional parameters (with default
values) using Python's keyword arg syntax. When providing a value to such a values) using Python's keyword arg syntax. When providing a value to such a
@ -186,7 +195,7 @@ This gives us the flexibility to re-order arguments and more importantly
to add new required arguments. It's also more explicit and easier to read. to add new required arguments. It's also more explicit and easier to read.
Properly defining optional arguments Properly defining optional arguments
######################## ####################################
It's always good to not initialize optional arguments at class creation, It's always good to not initialize optional arguments at class creation,
instead use ``**kwargs`` to get them. It's well known Telegram API can instead use ``**kwargs`` to get them. It's well known Telegram API can

View file

@ -17,4 +17,4 @@
files: ^telegram/.*\.py$ files: ^telegram/.*\.py$
args: args:
- --errors-only - --errors-only
- --disable=no-name-in-module,import-error - --disable=import-error

View file

@ -18,18 +18,20 @@ branches:
cache: cache:
directories: directories:
- $HOME/.cache/pip - $HOME/.cache/pip
- $HOME/.pre-commit
before_cache: before_cache:
- rm -f $HOME/.cache/pip/log/debug.log - rm -f $HOME/.cache/pip/log/debug.log
- rm -f $HOME/.pre-commit/pre-commit.log
install: install:
- pip install coveralls - pip install coveralls pytest-cov
- pip install -U wheel - pip install -U wheel
- pip install -r requirements.txt - pip install -U -r requirements.txt
- pip install -r requirements-dev.txt - pip install -U -r requirements-dev.txt
- if [[ $TRAVIS_PYTHON_VERSION != 'pypy'* ]]; then pip install ujson; fi - if [[ $TRAVIS_PYTHON_VERSION != 'pypy'* ]]; then pip install ujson; fi
script: script:
- python travis.py - pytest -v --cov=telegram
after_success: after_success:
coveralls coveralls

View file

@ -2,7 +2,7 @@
.PHONY: clean pep257 pep8 yapf lint test install .PHONY: clean pep257 pep8 yapf lint test install
PYLINT := pylint PYLINT := pylint
NOSETESTS := nosetests PYTEST := pytest
PEP257 := pep257 PEP257 := pep257
PEP8 := flake8 PEP8 := flake8
YAPF := yapf YAPF := yapf
@ -29,7 +29,7 @@ lint:
$(PYLINT) -E telegram --disable=no-name-in-module,import-error $(PYLINT) -E telegram --disable=no-name-in-module,import-error
test: test:
$(NOSETESTS) -v $(PYTEST) -v
install: install:
$(PIP) install -r requirements.txt -r requirements-dev.txt $(PIP) install -r requirements.txt -r requirements-dev.txt
@ -41,11 +41,11 @@ help:
@echo "- pep8 Check style with flake8" @echo "- pep8 Check style with flake8"
@echo "- lint Check style with pylint" @echo "- lint Check style with pylint"
@echo "- yapf Check style with yapf" @echo "- yapf Check style with yapf"
@echo "- test Run tests" @echo "- test Run tests using pytest"
@echo @echo
@echo "Available variables:" @echo "Available variables:"
@echo "- PYLINT default: $(PYLINT)" @echo "- PYLINT default: $(PYLINT)"
@echo "- NOSETESTS default: $(NOSETESTS)" @echo "- PYTEST default: $(PYTEST)"
@echo "- PEP257 default: $(PEP257)" @echo "- PEP257 default: $(PEP257)"
@echo "- PEP8 default: $(PEP8)" @echo "- PEP8 default: $(PEP8)"
@echo "- YAPF default: $(YAPF)" @echo "- YAPF default: $(YAPF)"

View file

@ -24,8 +24,4 @@ build: off
cache: C:\Users\appveyor\pip\wheels cache: C:\Users\appveyor\pip\wheels
test_script: test_script:
- "%python%\\Scripts\\nosetests -v --with-flaky --no-flaky-report tests" - "%python%\\Scripts\\pytest -v --cov=telegram"
after_test:
# This step builds your wheels.
- "%PYTHON%\\python.exe setup.py bdist_wheel"

View file

@ -1,10 +1,9 @@
flake8 flake8
nose
pep257 pep257
pylint pylint
flaky flaky
yapf yapf
pre-commit pre-commit
pre-commit-hooks
beautifulsoup4 beautifulsoup4
rednose pytest
pytest-timeout

View file

@ -17,3 +17,19 @@ ignore = W503
based_on_style = google based_on_style = google
split_before_logical_operator = True split_before_logical_operator = True
column_limit = 99 column_limit = 99
[tool:pytest]
testpaths = tests
addopts = --no-success-flaky-report -rsxX
filterwarnings =
error
ignore::DeprecationWarning
[coverage:run]
branch = False
source = telegram
omit =
tests/
telegram/__main__.py
telegram/vendor/*

View file

@ -1651,7 +1651,7 @@ class Bot(TelegramObject):
url_ = '{0}/setWebhook'.format(self.base_url) url_ = '{0}/setWebhook'.format(self.base_url)
# Backwards-compatibility: 'url' used to be named 'webhook_url' # Backwards-compatibility: 'url' used to be named 'webhook_url'
if 'webhook_url' in kwargs: if 'webhook_url' in kwargs: # pragma: no cover
warnings.warn("The 'webhook_url' parameter has been renamed to 'url' in accordance " warnings.warn("The 'webhook_url' parameter has been renamed to 'url' in accordance "
"with the API") "with the API")

View file

@ -90,7 +90,7 @@ class CallbackQuery(TelegramObject):
self.bot = bot self.bot = bot
self._id_attrs = ('id',) self._id_attrs = (self.id,)
@classmethod @classmethod
def de_json(cls, data, bot): def de_json(cls, data, bot):

View file

@ -135,12 +135,6 @@ class Dispatcher(object):
else: else:
self._set_singleton(None) self._set_singleton(None)
@classmethod
def _reset_singleton(cls):
# NOTE: This method was added mainly for test_updater benefit and specifically pypy. Never
# call it in production code.
cls.__singleton_semaphore.release()
def _init_async_threads(self, base_name, workers): def _init_async_threads(self, base_name, workers):
base_name = '{}_'.format(base_name) if base_name else '' base_name = '{}_'.format(base_name) if base_name else ''

View file

@ -68,7 +68,7 @@ class Game(TelegramObject):
self.description = description self.description = description
self.photo = photo self.photo = photo
self.text = text self.text = text
self.text_entities = text_entities self.text_entities = text_entities or list()
self.animation = animation self.animation = animation
@classmethod @classmethod

View file

@ -232,7 +232,7 @@ class Message(TelegramObject):
self.audio = audio self.audio = audio
self.game = game self.game = game
self.document = document self.document = document
self.photo = photo self.photo = photo or list()
self.sticker = sticker self.sticker = sticker
self.video = video self.video = video
self.voice = voice self.voice = voice
@ -242,10 +242,10 @@ class Message(TelegramObject):
self.location = location self.location = location
self.venue = venue self.venue = venue
self._new_chat_member = new_chat_member self._new_chat_member = new_chat_member
self.new_chat_members = new_chat_members self.new_chat_members = new_chat_members or list()
self.left_chat_member = left_chat_member self.left_chat_member = left_chat_member
self.new_chat_title = new_chat_title self.new_chat_title = new_chat_title
self.new_chat_photo = new_chat_photo self.new_chat_photo = new_chat_photo or list()
self.delete_chat_photo = bool(delete_chat_photo) self.delete_chat_photo = bool(delete_chat_photo)
self.group_chat_created = bool(group_chat_created) self.group_chat_created = bool(group_chat_created)
self.supergroup_chat_created = bool(supergroup_chat_created) self.supergroup_chat_created = bool(supergroup_chat_created)
@ -330,7 +330,7 @@ class Message(TelegramObject):
for i in (self.audio, self.game, self.document, self.photo, self.sticker, for i in (self.audio, self.game, self.document, self.photo, self.sticker,
self.video, self.voice, self.video_note, self.contact, self.location, self.video, self.voice, self.video_note, self.contact, self.location,
self.venue, self.invoice, self.successful_payment): self.venue, self.invoice, self.successful_payment):
if i is not None: if i:
self._effective_attachment = i self._effective_attachment = i
break break
else: else:

View file

@ -139,7 +139,8 @@ class Update(TelegramObject):
""" """
:class:`telegram.Chat`: The chat that this update was sent in, no matter what kind of :class:`telegram.Chat`: The chat that this update was sent in, no matter what kind of
update this is. Will be ``None`` for :attr:`inline_query`, update this is. Will be ``None`` for :attr:`inline_query`,
:attr:`chosen_inline_result`, :attr:`shipping_query` and :attr:`pre_checkout_query`. :attr:`chosen_inline_result`, :attr:`callback_query` from inline messages,
:attr:`shipping_query` and :attr:`pre_checkout_query`.
""" """
if self._effective_chat: if self._effective_chat:

View file

@ -34,7 +34,7 @@ try:
import telegram.vendor.ptb_urllib3.urllib3.contrib.appengine as appengine import telegram.vendor.ptb_urllib3.urllib3.contrib.appengine as appengine
from telegram.vendor.ptb_urllib3.urllib3.connection import HTTPConnection from telegram.vendor.ptb_urllib3.urllib3.connection import HTTPConnection
from telegram.vendor.ptb_urllib3.urllib3.util.timeout import Timeout from telegram.vendor.ptb_urllib3.urllib3.util.timeout import Timeout
except ImportError: except ImportError: # pragma: no cover
warnings.warn("python-telegram-bot wasn't properly installed. Please refer to README.rst on " warnings.warn("python-telegram-bot wasn't properly installed. Please refer to README.rst on "
"how to properly install.") "how to properly install.")
raise raise

View file

@ -1,5 +0,0 @@
tests
=====
Some tests fail because of weird behaviour of the Telegram API. We comment these
out and mark them with a `TODO` comment.

View file

@ -1,106 +0,0 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents a Base class for tests"""
import os
import signal
import sys
from nose.tools import make_decorator
from tests.bots import get_bot
sys.path.append('.')
import json
import telegram
class BaseTest(object):
"""This object represents a Base test and its sets of functions."""
_group_id = None
_channel_id = None
_bot = None
_chat_id = None
_payment_provider_token = None
@classmethod
def setUpClass(cls):
bot_info = get_bot()
cls._chat_id = bot_info['chat_id']
cls._bot = telegram.Bot(bot_info['token'])
cls._group_id = bot_info['group_id']
cls._channel_id = bot_info['channel_id']
cls._payment_provider_token = bot_info['payment_provider_token']
@staticmethod
def is_json(string):
try:
json.loads(string)
except ValueError:
return False
return True
@staticmethod
def is_dict(dictionary):
if isinstance(dictionary, dict):
return True
return False
class TestTimedOut(AssertionError):
def __init__(self, time_limit, frame):
super(TestTimedOut, self).__init__('time_limit={0}'.format(time_limit))
self.time_limit = time_limit
self.frame = frame
def timeout(time_limit):
def decorator(func):
def timed_out(_signum, frame):
raise TestTimedOut(time_limit, frame)
def newfunc(*args, **kwargs):
try:
# Will only work on unix systems
orig_handler = signal.signal(signal.SIGALRM, timed_out)
signal.alarm(time_limit)
except AttributeError:
pass
try:
rc = func(*args, **kwargs)
finally:
try:
# Will only work on unix systems
signal.alarm(0)
signal.signal(signal.SIGALRM, orig_handler)
except AttributeError:
pass
return rc
newfunc = make_decorator(func)(newfunc)
return newfunc
return decorator

View file

@ -5,62 +5,51 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""Provide a bot to tests""" """Provide a bot to tests"""
import os import os
import sys import sys
from platform import python_implementation
bot_settings = { # Provide some public fallbacks so it's easy for contributors to run tests on their local machine
'APPVEYOR': FALLBACKS = {
{
'token': '133505823:AAHZFMHno3mzVLErU5b5jJvaeG--qUyLyG0', 'token': '133505823:AAHZFMHno3mzVLErU5b5jJvaeG--qUyLyG0',
'payment_provider_token': '284685063:TEST:ZGJlMmQxZDI3ZTc3' 'payment_provider_token': '284685063:TEST:ZGJlMmQxZDI3ZTc3',
},
'TRAVIS':
{
'token': '133505823:AAHZFMHno3mzVLErU5b5jJvaeG--qUyLyG0',
'payment_provider_token': '284685063:TEST:ZGJlMmQxZDI3ZTc3'
},
'FALLBACK':
{
'token': '133505823:AAHZFMHno3mzVLErU5b5jJvaeG--qUyLyG0',
'payment_provider_token': '284685063:TEST:ZGJlMmQxZDI3ZTc3'
}
}
def get_bot():
# TODO: Add version info with different bots
# ver = sys.version_info
# pyver = "{}{}".format(ver[0], ver[1])
#
bot = None
if os.environ.get('TRAVIS', False):
bot = bot_settings.get('TRAVIS', None)
# TODO:
# bot = bot_setting.get('TRAVIS'+pyver, None)
elif os.environ.get('APPVEYOR', False):
bot = bot_settings.get('APPVEYOR', None)
# TODO:
# bot = bot_setting.get('TRAVIS'+pyver, None)
if not bot:
bot = bot_settings['FALLBACK']
bot.update({
'chat_id': '12173560', 'chat_id': '12173560',
'group_id': '-49740850', 'group_id': '-49740850',
'channel_id': '@pythontelegrambottests' 'channel_id': '@pythontelegrambottests'
}) }
return bot
def get(name, fallback):
full_name = '{0}-{1}-{2[0]}{2[1]}'.format(name, python_implementation(),
sys.version_info).upper()
# First try fullnames such as
# TOKEN-CPYTHON-33
# CHAT_ID-PYPY-27
val = os.getenv(full_name)
if val:
return val
# Then try short names
# TOKEN
# CHAT_ID
val = os.getenv(name.upper())
if val:
return val
# Otherwise go with the fallback
return fallback
def get_bot():
return {k: get(k, v) for k, v in FALLBACKS.items()}

111
tests/conftest.py Normal file
View file

@ -0,0 +1,111 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
import os
import sys
from collections import defaultdict
from queue import Queue
from threading import Thread, Event
from time import sleep
import pytest
from telegram import Bot
from telegram.ext import Dispatcher, JobQueue
from tests.bots import get_bot
TRAVIS = os.getenv('TRAVIS', False)
if TRAVIS:
pytest_plugins = ['tests.travis_fold']
@pytest.fixture(scope='session')
def bot_info():
return get_bot()
@pytest.fixture(scope='session')
def bot(bot_info):
return Bot(bot_info['token'])
@pytest.fixture(scope='session')
def chat_id(bot_info):
return bot_info['chat_id']
@pytest.fixture(scope='session')
def group_id(bot_info):
return bot_info['group_id']
@pytest.fixture(scope='session')
def channel_id(bot_info):
return bot_info['channel_id']
@pytest.fixture(scope='session')
def provider_token(bot_info):
return bot_info['payment_provider_token']
def create_dp(bot):
# Dispatcher is heavy to init (due to many threads and such) so we have a single session
# scoped one here, but before each test, reset it (dp fixture below)
dispatcher = Dispatcher(bot, Queue(), job_queue=JobQueue(bot), workers=2)
thr = Thread(target=dispatcher.start)
thr.start()
sleep(2)
yield dispatcher
sleep(1)
if dispatcher.running:
dispatcher.stop()
thr.join()
@pytest.fixture(scope='session')
def _dp(bot):
for dp in create_dp(bot):
yield dp
@pytest.fixture(scope='function')
def dp(_dp):
# Reset the dispatcher first
while not _dp.update_queue.empty():
_dp.update_queue.get(False)
_dp.chat_data = defaultdict(dict)
_dp.user_data = defaultdict(dict)
_dp.handlers = {}
_dp.groups = []
_dp.error_handlers = []
_dp.__stop_event = Event()
_dp.__exception_event = Event()
_dp.__async_queue = Queue()
_dp.__async_threads = set()
if _dp._Dispatcher__singleton_semaphore.acquire(blocking=0):
Dispatcher._set_singleton(_dp)
yield _dp
Dispatcher._Dispatcher__singleton_semaphore.release()
def pytest_configure(config):
if sys.version_info >= (3,):
config.addinivalue_line('filterwarnings', 'ignore::ResourceWarning')
# TODO: Write so good code that we don't need to ignore ResourceWarnings anymore

Binary file not shown.

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

View file

@ -5,87 +5,79 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram Animation"""
import unittest import pytest
import sys
sys.path.append('.') from telegram import PhotoSize, Animation, Voice
import telegram
from tests.base import BaseTest
class AnimationTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram Animation.""" def thumb():
return PhotoSize(height=50, file_size=1613, file_id='AAQEABPQUWQZAAT7gZuQAAH0bd93VwACAg',
width=90)
def setUp(self):
self.animation_file_id = 'CgADBAADFQEAAny4rAUgukhiTv2TWwI'
self.thumb = telegram.PhotoSize.de_json({
'height': 50,
'file_size': 1613,
'file_id': 'AAQEABPQUWQZAAT7gZuQAAH0bd93VwACAg',
'width': 90
}, self._bot)
self.file_name = "game.gif.mp4"
self.mime_type = "video/mp4"
self.file_size = 4008
self.json_dict = { @pytest.fixture(scope='class')
def animation(thumb, bot):
return Animation(TestAnimation.animation_file_id, thumb=thumb.to_dict(),
file_name=TestAnimation.file_name, mime_type=TestAnimation.mime_type,
file_size=TestAnimation.file_size, bot=bot)
class TestAnimation(object):
animation_file_id = 'CgADBAADFQEAAny4rAUgukhiTv2TWwI'
file_name = 'game.gif.mp4'
mime_type = 'video/mp4'
file_size = 4008
def test_de_json(self, bot, thumb):
json_dict = {
'file_id': self.animation_file_id, 'file_id': self.animation_file_id,
'thumb': self.thumb.to_dict(), 'thumb': thumb.to_dict(),
'file_name': self.file_name, 'file_name': self.file_name,
'mime_type': self.mime_type, 'mime_type': self.mime_type,
'file_size': self.file_size 'file_size': self.file_size
} }
animation = Animation.de_json(json_dict, bot)
assert animation.file_id == self.animation_file_id
assert animation.thumb == thumb
assert animation.file_name == self.file_name
assert animation.mime_type == self.mime_type
assert animation.file_size == self.file_size
def test_animation_de_json(self): def test_to_dict(self, animation, thumb):
animation = telegram.Animation.de_json(self.json_dict, self._bot) animation_dict = animation.to_dict()
self.assertEqual(animation.file_id, self.animation_file_id) assert isinstance(animation_dict, dict)
self.assertEqual(animation.thumb, self.thumb) assert animation_dict['file_id'] == animation.file_id
self.assertEqual(animation.file_name, self.file_name) assert animation_dict['thumb'] == thumb.to_dict()
self.assertEqual(animation.mime_type, self.mime_type) assert animation_dict['file_name'] == animation.file_name
self.assertEqual(animation.file_size, self.file_size) assert animation_dict['mime_type'] == animation.mime_type
assert animation_dict['file_size'] == animation.file_size
def test_animation_to_json(self):
animation = telegram.Animation.de_json(self.json_dict, self._bot)
self.assertTrue(self.is_json(animation.to_json()))
def test_animation_to_dict(self):
animation = telegram.Animation.de_json(self.json_dict, self._bot)
self.assertTrue(self.is_dict(animation.to_dict()))
self.assertEqual(animation.file_id, self.animation_file_id)
self.assertEqual(animation.thumb, self.thumb)
self.assertEqual(animation.file_name, self.file_name)
self.assertEqual(animation.mime_type, self.mime_type)
self.assertEqual(animation.file_size, self.file_size)
def test_equality(self): def test_equality(self):
a = telegram.Animation(self.animation_file_id) a = Animation(self.animation_file_id)
b = telegram.Animation(self.animation_file_id) b = Animation(self.animation_file_id)
d = telegram.Animation("") d = Animation('')
e = telegram.Voice(self.animation_file_id, 0) e = Voice(self.animation_file_id, 0)
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
self.assertNotEqual(a, e) assert a != e
self.assertNotEqual(hash(a), hash(e)) assert hash(a) != hash(e)

View file

@ -5,248 +5,182 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram Audio"""
import os import os
import unittest
import pytest
from flaky import flaky from flaky import flaky
import telegram from telegram import Audio, TelegramError, Voice
from tests.base import BaseTest, timeout
class AudioTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='function')
"""This object represents Tests for Telegram Audio.""" def audio_file():
f = open('tests/data/telegram.mp3', 'rb')
yield f
f.close()
@classmethod
def setUpClass(cls):
super(AudioTest, cls).setUpClass()
cls.caption = "Test audio" @pytest.fixture(scope='class')
cls.performer = 'Leandro Toledo' def audio(bot, chat_id):
cls.title = 'Teste' with open('tests/data/telegram.mp3', 'rb') as f:
# cls.audio_file_url = 'https://python-telegram-bot.org/static/testfiles/telegram.mp3' return bot.send_audio(chat_id, audio=f, timeout=10).audio
class TestAudio(object):
caption = 'Test audio'
performer = 'Leandro Toledo'
title = 'Teste'
duration = 3
# audio_file_url = 'https://python-telegram-bot.org/static/testfiles/telegram.mp3'
# Shortened link, the above one is cached with the wrong duration. # Shortened link, the above one is cached with the wrong duration.
cls.audio_file_url = "https://goo.gl/3En24v" audio_file_url = 'https://goo.gl/3En24v'
mime_type = 'audio/mpeg'
audio_file = open('tests/data/telegram.mp3', 'rb') file_size = 122920
audio = cls._bot.send_audio(cls._chat_id, audio=audio_file, timeout=10).audio
cls.audio = audio
def test_creation(self, audio):
# Make sure file has been uploaded. # Make sure file has been uploaded.
# Simple assertions PY2 Only assert isinstance(audio, Audio)
assert isinstance(cls.audio, telegram.Audio) assert isinstance(audio.file_id, str)
assert isinstance(cls.audio.file_id, str) assert audio.file_id is not ''
assert cls.audio.file_id is not ''
def setUp(self): def test_expected_values(self, audio):
self.audio_file = open('tests/data/telegram.mp3', 'rb') assert audio.duration == self.duration
self.json_dict = { assert audio.performer is None
'file_id': self.audio.file_id, assert audio.title is None
'duration': self.audio.duration, assert audio.mime_type == self.mime_type
'performer': self.performer, assert audio.file_size == self.file_size
'title': self.title,
'caption': self.caption,
'mime_type': self.audio.mime_type,
'file_size': self.audio.file_size
}
def test_expected_values(self):
self.assertEqual(self.audio.duration, 3)
self.assertEqual(self.audio.performer, None)
self.assertEqual(self.audio.title, None)
self.assertEqual(self.audio.mime_type, 'audio/mpeg')
self.assertEqual(self.audio.file_size, 122920)
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_send_audio_all_args(self): def test_send_all_args(self, bot, chat_id, audio_file):
message = self._bot.sendAudio( message = bot.send_audio(chat_id, audio=audio_file, caption=self.caption,
self._chat_id, duration=self.duration, performer=self.performer,
self.audio_file, title=self.title, disable_notification=False)
caption=self.caption,
duration=self.audio.duration,
performer=self.performer,
title=self.title,
disable_notification=False)
self.assertEqual(message.caption, self.caption) assert message.caption == self.caption
audio = message.audio assert isinstance(message.audio, Audio)
assert isinstance(message.audio.file_id, str)
self.assertIsInstance(audio, telegram.Audio) assert message.audio.file_id is not None
self.assertIsInstance(audio.file_id, str) assert message.audio.duration == self.duration
self.assertNotEqual(audio.file_id, None) assert message.audio.performer == self.performer
self.assertEqual(audio.duration, self.audio.duration) assert message.audio.title == self.title
self.assertEqual(audio.performer, self.performer) assert message.audio.mime_type == self.mime_type
self.assertEqual(audio.title, self.title) assert message.audio.file_size == self.file_size
self.assertEqual(audio.mime_type, self.audio.mime_type)
self.assertEqual(audio.file_size, self.audio.file_size)
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_get_and_download_audio(self): def test_get_and_download(self, bot, audio):
new_file = self._bot.getFile(self.audio.file_id) new_file = bot.get_file(audio.file_id)
self.assertEqual(new_file.file_size, self.audio.file_size) assert new_file.file_size == self.file_size
self.assertEqual(new_file.file_id, self.audio.file_id) assert new_file.file_id == audio.file_id
self.assertTrue(new_file.file_path.startswith('https://')) assert new_file.file_path.startswith('https://')
new_file.download('telegram.mp3') new_file.download('telegram.mp3')
self.assertTrue(os.path.isfile('telegram.mp3')) assert os.path.isfile('telegram.mp3')
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_send_audio_mp3_url_file(self): def test_send_mp3_url_file(self, bot, chat_id, audio):
message = self._bot.sendAudio(chat_id=self._chat_id, audio=self.audio_file_url) message = bot.send_audio(chat_id=chat_id, audio=self.audio_file_url, caption=self.caption)
audio = message.audio assert message.caption == self.caption
self.assertIsInstance(audio, telegram.Audio) assert isinstance(message.audio, Audio)
self.assertIsInstance(audio.file_id, str) assert isinstance(message.audio.file_id, str)
self.assertNotEqual(audio.file_id, None) assert message.audio.file_id is not None
self.assertEqual(audio.duration, self.audio.duration) assert message.audio.duration == audio.duration
self.assertEqual(audio.mime_type, self.audio.mime_type) assert message.audio.mime_type == audio.mime_type
self.assertEqual(audio.file_size, self.audio.file_size) assert message.audio.file_size == audio.file_size
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_send_audio_mp3_url_file_with_caption(self): def test_resend(self, bot, chat_id, audio):
message = self._bot.sendAudio( message = bot.send_audio(chat_id=chat_id, audio=audio.file_id)
chat_id=self._chat_id,
audio=self.audio_file_url,
caption=self.caption)
self.assertEqual(message.caption, self.caption) assert message.audio == audio
audio = message.audio def test_send_with_audio(self, monkeypatch, bot, chat_id, audio):
def test(_, url, data, **kwargs):
return data['audio'] == audio.file_id
self.assertIsInstance(audio, telegram.Audio) monkeypatch.setattr('telegram.utils.request.Request.post', test)
self.assertIsInstance(audio.file_id, str) message = bot.send_audio(audio=audio, chat_id=chat_id)
self.assertNotEqual(audio.file_id, None) assert message
self.assertEqual(audio.duration, self.audio.duration)
self.assertEqual(audio.mime_type, self.audio.mime_type) def test_de_json(self, bot):
self.assertEqual(audio.file_size, self.audio.file_size) json_dict = {'file_id': 'not a file id',
'duration': self.duration,
'performer': self.performer,
'title': self.title,
'caption': self.caption,
'mime_type': self.mime_type,
'file_size': self.file_size}
json_audio = Audio.de_json(json_dict, bot)
assert json_audio.file_id == 'not a file id'
assert json_audio.duration == self.duration
assert json_audio.performer == self.performer
assert json_audio.title == self.title
assert json_audio.mime_type == self.mime_type
assert json_audio.file_size == self.file_size
def test_to_dict(self, audio):
audio_dict = audio.to_dict()
assert isinstance(audio_dict, dict)
assert audio_dict['file_id'] == audio.file_id
assert audio_dict['duration'] == audio.duration
assert audio_dict['mime_type'] == audio.mime_type
assert audio_dict['file_size'] == audio.file_size
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_send_audio_resend(self): def test_error_send_empty_file(self, bot, chat_id):
message = self._bot.sendAudio( audio_file = open(os.devnull, 'rb')
chat_id=self._chat_id,
audio=self.audio.file_id)
audio = message.audio with pytest.raises(TelegramError):
bot.send_audio(chat_id=chat_id, audio=audio_file)
self.assertEqual(audio, self.audio)
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_send_audio_with_audio(self): def test_error_send_empty_file_id(self, bot, chat_id):
message = self._bot.send_audio(audio=self.audio, chat_id=self._chat_id) with pytest.raises(TelegramError):
audio = message.audio bot.send_audio(chat_id=chat_id, audio='')
self.assertEqual(audio, self.audio) def test_error_send_without_required_args(self, bot, chat_id):
with pytest.raises(TypeError):
bot.send_audio(chat_id=chat_id)
def test_audio_de_json(self): def test_equality(self, audio):
audio = telegram.Audio.de_json(self.json_dict, self._bot) a = Audio(audio.file_id, audio.duration)
b = Audio(audio.file_id, audio.duration)
c = Audio(audio.file_id, 0)
d = Audio('', audio.duration)
e = Voice(audio.file_id, audio.duration)
self.assertIsInstance(audio, telegram.Audio) assert a == b
self.assertEqual(audio.file_id, self.audio.file_id) assert hash(a) == hash(b)
self.assertEqual(audio.duration, self.audio.duration) assert a is not b
self.assertEqual(audio.performer, self.performer)
self.assertEqual(audio.title, self.title)
self.assertEqual(audio.mime_type, self.audio.mime_type)
self.assertEqual(audio.file_size, self.audio.file_size)
def test_audio_to_json(self): assert a == c
self.assertTrue(self.is_json(self.audio.to_json())) assert hash(a) == hash(c)
def test_audio_to_dict(self): assert a != d
audio = self.audio.to_dict() assert hash(a) != hash(d)
self.assertTrue(self.is_dict(audio)) assert a != e
self.assertEqual(audio['file_id'], self.audio.file_id) assert hash(a) != hash(e)
self.assertEqual(audio['duration'], self.audio.duration)
self.assertEqual(audio['mime_type'], self.audio.mime_type)
self.assertEqual(audio['file_size'], self.audio.file_size)
@flaky(3, 1)
@timeout(10)
def test_error_send_audio_empty_file(self):
json_dict = self.json_dict
del (json_dict['file_id'])
json_dict['audio'] = open(os.devnull, 'rb')
with self.assertRaises(telegram.TelegramError):
self._bot.sendAudio(chat_id=self._chat_id, **json_dict)
@flaky(3, 1)
@timeout(10)
def test_error_send_audio_empty_file_id(self):
json_dict = self.json_dict
del (json_dict['file_id'])
json_dict['audio'] = ''
with self.assertRaises(telegram.TelegramError):
self._bot.sendAudio(chat_id=self._chat_id, **json_dict)
@flaky(3, 1)
@timeout(10)
def test_error_audio_without_required_args(self):
json_dict = self.json_dict
del (json_dict['file_id'])
del (json_dict['duration'])
with self.assertRaises(TypeError):
self._bot.sendAudio(chat_id=self._chat_id, **json_dict)
@flaky(3, 1)
@timeout(10)
def test_reply_audio(self):
"""Test for Message.reply_audio"""
message = self._bot.sendMessage(self._chat_id, '.')
audio = message.reply_audio(self.audio_file).audio
self.assertIsInstance(audio, telegram.Audio)
self.assertIsInstance(audio.file_id, str)
self.assertNotEqual(audio.file_id, None)
def test_equality(self):
a = telegram.Audio(self.audio.file_id, self.audio.duration)
b = telegram.Audio(self.audio.file_id, self.audio.duration)
c = telegram.Audio(self.audio.file_id, 0)
d = telegram.Audio("", self.audio.duration)
e = telegram.Voice(self.audio.file_id, self.audio.duration)
self.assertEqual(a, b)
self.assertEqual(hash(a), hash(b))
self.assertIsNot(a, b)
self.assertEqual(a, c)
self.assertEqual(hash(a), hash(c))
self.assertNotEqual(a, d)
self.assertNotEqual(hash(a), hash(d))
self.assertNotEqual(a, e)
self.assertNotEqual(hash(a), hash(e))
if __name__ == '__main__':
unittest.main()

View file

@ -1,424 +1,618 @@
#!/usr/bin/env python #!/usr/bin/env python
# encoding: utf-8
# #
# A library that provides a Python interface to the Telegram Bot API # A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017 # Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram Bot"""
import io
import re
from datetime import datetime
import time import time
import sys from datetime import datetime, timedelta
import unittest from platform import python_implementation
import pytest
from flaky import flaky from flaky import flaky
from future.utils import string_types
sys.path.append('.') from telegram import (Bot, Update, ChatAction, TelegramError, User, InlineKeyboardMarkup,
InlineKeyboardButton, InlineQueryResultArticle, InputTextMessageContent,
import telegram ShippingOption, LabeledPrice)
from telegram.utils.request import Request from telegram.error import BadRequest, InvalidToken, NetworkError, RetryAfter, TimedOut
from telegram.error import BadRequest from telegram.utils.helpers import from_timestamp
from tests.base import BaseTest, timeout
BASE_TIME = time.time() BASE_TIME = time.time()
HIGHSCORE_DELTA = 1450000000 HIGHSCORE_DELTA = 1450000000
def _stall_retry(*_args, **_kwargs): @pytest.fixture(scope='class')
time.sleep(3) def message(bot, chat_id):
return True return bot.send_message(chat_id, 'Text', reply_to_message_id=1,
disable_web_page_preview=True, disable_notification=True)
class BotTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram Bot.""" def media_message(bot, chat_id):
with open('tests/data/telegram.ogg', 'rb') as f:
return bot.send_voice(chat_id, voice=f, caption='my caption', timeout=10)
class TestBot(object):
@pytest.mark.parametrize('token', argvalues=[
'123',
'12a:abcd1234',
'12:abcd1234',
'1234:abcd1234\n',
' 1234:abcd1234',
' 1234:abcd1234\r',
'1234:abcd 1234'
])
def test_invalid_token(self, token):
with pytest.raises(InvalidToken, match='Invalid token'):
Bot(token)
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def testGetMe(self): def test_invalid_token_server_response(self, monkeypatch):
bot = self._bot.getMe() monkeypatch.setattr('telegram.Bot._validate_token', lambda x, y: True)
bot = Bot('12')
self.assertTrue(self.is_json(bot.to_json())) with pytest.raises(InvalidToken):
self._testUserEqualsBot(bot) bot.get_me()
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def testSendMessage(self): def test_get_me_and_properties(self, bot):
message = self._bot.sendMessage( get_me_bot = bot.get_me()
chat_id=self._chat_id, text='Моё судно на воздушной подушке полно угрей')
self.assertTrue(self.is_json(message.to_json())) assert isinstance(get_me_bot, User)
self.assertEqual(message.text, u'Моё судно на воздушной подушке полно угрей') assert get_me_bot.id == bot.id
self.assertTrue(isinstance(message.date, datetime)) assert get_me_bot.username == bot.username
assert get_me_bot.first_name == bot.first_name
assert get_me_bot.last_name == bot.last_name
assert get_me_bot.name == bot.name
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def testSilentSendMessage(self): def test_forward_message(self, bot, chat_id, message):
message = self._bot.sendMessage( message = bot.forward_message(chat_id, from_chat_id=chat_id, message_id=message.message_id)
chat_id=self._chat_id,
text='Моё судно на воздушной подушке полно угрей',
disable_notification=True)
self.assertTrue(self.is_json(message.to_json())) assert message.text == message.text
self.assertEqual(message.text, u'Моё судно на воздушной подушке полно угрей') assert message.forward_from.username == message.from_user.username
self.assertTrue(isinstance(message.date, datetime)) assert isinstance(message.forward_date, datetime)
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_sendMessage_no_web_page_preview(self): def test_delete_message(self, bot, chat_id):
message = self._bot.sendMessage( message = bot.send_message(chat_id, text='will be deleted')
chat_id=self._chat_id,
text='Моё судно на воздушной подушке полно угрей', assert bot.delete_message(chat_id=chat_id, message_id=message.message_id) is True
@flaky(3, 1)
@pytest.mark.timeout(10)
def test_delete_message_old_message(self, bot, chat_id):
with pytest.raises(TelegramError, match='can\'t be deleted'):
# Considering that the first message is old enough
bot.delete_message(chat_id=chat_id, message_id=1)
# send_photo, send_audio, send_document, send_sticker, send_video, send_voice
# and send_video_note are tested in their respective test modules. No need to duplicate here.
@flaky(3, 1)
@pytest.mark.timeout(10)
def test_send_location(self, bot, chat_id):
message = bot.send_location(chat_id=chat_id, latitude=-23.691288, longitude=-46.788279)
assert message.location
assert message.location.longitude == -46.788279
assert message.location.latitude == -23.691288
@flaky(3, 1)
@pytest.mark.timeout(10)
def test_send_venue(self, bot, chat_id):
longitude = -46.788279
latitude = -23.691288
title = 'title'
address = 'address'
message = bot.send_venue(chat_id=chat_id, title=title, address=address, latitude=latitude,
longitude=longitude)
assert message.venue
assert message.venue.title == title
assert message.venue.address == address
assert message.venue.location.latitude == latitude
assert message.venue.location.longitude == longitude
@flaky(3, 1)
@pytest.mark.timeout(10)
@pytest.mark.xfail(raises=RetryAfter)
@pytest.mark.skipif(python_implementation() == 'PyPy',
reason='Unstable on pypy for some reason')
def test_send_contact(self, bot, chat_id):
phone_number = '+11234567890'
first_name = 'Leandro'
last_name = 'Toledo'
message = bot.send_contact(chat_id=chat_id, phone_number=phone_number,
first_name=first_name, last_name=last_name)
assert message.contact
assert message.contact.phone_number == phone_number
assert message.contact.first_name == first_name
assert message.contact.last_name == last_name
@flaky(3, 1)
@pytest.mark.timeout(10)
def test_send_game(self, bot, chat_id):
game_short_name = 'python_telegram_bot_test_game'
message = bot.send_game(chat_id, game_short_name)
assert message.game
assert message.game.description == 'This is a test game for python-telegram-bot.'
assert message.game.animation.file_id == 'CgADAQADKwIAAvjAuQABozciVqhFDO0C'
assert message.game.photo[0].file_size == 851
@flaky(3, 1)
@pytest.mark.timeout(10)
def test_send_chat_action(self, bot, chat_id):
assert bot.send_chat_action(chat_id, ChatAction.TYPING)
# TODO: Needs improvement. We need incoming inline query to test answer.
def test_answer_inline_query(self, monkeypatch, bot):
# For now just test that our internals pass the correct data
def test(_, url, data, *args, **kwargs):
return data == {'cache_time': 300,
'results': [{'title': 'first', 'id': '11', 'type': 'article',
'input_message_content': {'message_text': 'first'}},
{'title': 'second', 'id': '12', 'type': 'article',
'input_message_content': {'message_text': 'second'}}],
'next_offset': '42', 'switch_pm_parameter': 'start_pm',
'inline_query_id': 1234, 'is_personal': True,
'switch_pm_text': 'switch pm'}
monkeypatch.setattr('telegram.utils.request.Request.post', test)
results = [InlineQueryResultArticle('11', 'first', InputTextMessageContent('first')),
InlineQueryResultArticle('12', 'second', InputTextMessageContent('second'))]
assert bot.answer_inline_query(1234,
results=results,
cache_time=300,
is_personal=True,
next_offset='42',
switch_pm_text='switch pm',
switch_pm_parameter='start_pm')
@flaky(3, 1)
@pytest.mark.timeout(10)
def test_get_user_profile_photos(self, bot, chat_id):
user_profile_photos = bot.get_user_profile_photos(chat_id)
assert user_profile_photos.photos[0][0].file_size == 12421
@flaky(3, 1)
@pytest.mark.timeout(10)
def test_get_one_user_profile_photo(self, bot, chat_id):
user_profile_photos = bot.get_user_profile_photos(chat_id, offset=0, limit=1)
assert user_profile_photos.photos[0][0].file_size == 12421
# get_file is tested multiple times in the test_*media* modules.
# TODO: Needs improvement. No feasable way to test until bots can add members.
def test_kick_chat_member(self, monkeypatch, bot):
def test(_, url, data, *args, **kwargs):
chat_id = data['chat_id'] == 2
user_id = data['user_id'] == 32
until_date = data.get('until_date', 1577887200) == 1577887200
return chat_id and user_id and until_date
monkeypatch.setattr('telegram.utils.request.Request.post', test)
until = from_timestamp(1577887200)
assert bot.kick_chat_member(2, 32)
assert bot.kick_chat_member(2, 32, until_date=until)
assert bot.kick_chat_member(2, 32, until_date=1577887200)
# TODO: Needs improvement.
def test_unban_chat_member(self, monkeypatch, bot):
def test(_, url, data, *args, **kwargs):
chat_id = data['chat_id'] == 2
user_id = data['user_id'] == 32
return chat_id and user_id
monkeypatch.setattr('telegram.utils.request.Request.post', test)
assert bot.unban_chat_member(2, 32)
# TODO: Needs improvement. Need an incoming callbackquery to test
def test_answer_callback_query(self, monkeypatch, bot):
# For now just test that our internals pass the correct data
def test(_, url, data, *args, **kwargs):
return data == {'callback_query_id': 23, 'show_alert': True, 'url': 'no_url',
'cache_time': 1, 'text': 'answer'}
monkeypatch.setattr('telegram.utils.request.Request.post', test)
assert bot.answer_callback_query(23, text='answer', show_alert=True, url='no_url',
cache_time=1)
@flaky(3, 1)
@pytest.mark.timeout(10)
def test_edit_message_text(self, bot, message):
message = bot.edit_message_text(text='new_text', chat_id=message.chat_id,
message_id=message.message_id, parse_mode='HTML',
disable_web_page_preview=True) disable_web_page_preview=True)
self.assertTrue(self.is_json(message.to_json())) assert message.text == 'new_text'
self.assertEqual(message.text, u'Моё судно на воздушной подушке полно угрей')
@pytest.mark.skip(reason='need reference to an inline message')
def test_edit_message_text_inline(self):
pass
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_deleteMessage(self): def test_edit_message_caption(self, bot, media_message):
message = self._bot.send_message( message = bot.edit_message_caption(caption='new_caption', chat_id=media_message.chat_id,
chat_id=self._chat_id, text='This message will be deleted') message_id=media_message.message_id)
self.assertTrue( assert message.caption == 'new_caption'
self._bot.delete_message(
chat_id=self._chat_id, message_id=message.message_id)) @pytest.mark.xfail(raises=TelegramError) # TODO: remove when #744 is merged
def test_edit_message_caption_without_required(self, bot):
with pytest.raises(ValueError, match='Both chat_id and message_id are required when'):
bot.edit_message_caption(caption='new_caption')
@pytest.mark.skip(reason='need reference to an inline message')
def test_edit_message_caption_inline(self):
pass
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_deleteMessage_old_message(self): def test_edit_reply_markup(self, bot, message):
with self.assertRaisesRegexp(telegram.TelegramError, "can't be deleted"): new_markup = InlineKeyboardMarkup([[InlineKeyboardButton(text='test', callback_data='1')]])
# Considering that the first message is old enough message = bot.edit_message_reply_markup(chat_id=message.chat_id,
self._bot.delete_message(chat_id=self._chat_id, message_id=1) message_id=message.message_id,
reply_markup=new_markup)
assert message is not True
@pytest.mark.xfail(raises=TelegramError) # TODO: remove when #744 is merged
def test_edit_message_reply_markup_without_required(self, bot):
new_markup = InlineKeyboardMarkup([[InlineKeyboardButton(text='test', callback_data='1')]])
with pytest.raises(ValueError, match='Both chat_id and message_id are required when'):
bot.edit_message_reply_markup(reply_markup=new_markup)
@pytest.mark.skip(reason='need reference to an inline message')
def test_edit_reply_markup_inline(self):
pass
# TODO: Actually send updates to the test bot so this can be tested properly
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def testGetUpdates(self): def test_get_updates(self, bot):
self._bot.delete_webhook() # make sure there is no webhook set if webhook tests failed bot.delete_webhook() # make sure there is no webhook set if webhook tests failed
updates = self._bot.getUpdates(timeout=1) updates = bot.get_updates(timeout=1)
assert isinstance(updates, list)
if updates: if updates:
self.assertTrue(self.is_json(updates[0].to_json())) assert isinstance(updates[0], Update)
self.assertTrue(isinstance(updates[0], telegram.Update))
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(15)
def testForwardMessage(self): @pytest.mark.xfail
message = self._bot.forwardMessage( def test_set_webhook_get_webhook_info_and_delete_webhook(self, bot):
chat_id=self._chat_id, from_chat_id=self._chat_id, message_id=2398) url = 'https://python-telegram-bot.org/test/webhook'
max_connections = 7
self.assertTrue(self.is_json(message.to_json())) allowed_updates = ['message']
self.assertEqual(message.text, 'teste') bot.set_webhook(url, max_connections=max_connections, allowed_updates=allowed_updates)
self.assertEqual(message.forward_from.username, 'leandrotoledo') time.sleep(2)
self.assertTrue(isinstance(message.forward_date, datetime)) live_info = bot.get_webhook_info()
time.sleep(6)
bot.delete_webhook()
time.sleep(2)
info = bot.get_webhook_info()
assert info.url == ''
assert live_info.url == url
assert live_info.max_connections == max_connections
assert live_info.allowed_updates == allowed_updates
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def testSendGame(self): def test_leave_chat(self, bot):
game_short_name = 'python_telegram_bot_test_game' with pytest.raises(BadRequest, match='Chat not found'):
message = self._bot.sendGame(game_short_name=game_short_name, chat_id=self._chat_id) bot.leave_chat(-123456)
self.assertTrue(self.is_json(message.to_json())) with pytest.raises(NetworkError, match='Chat not found'):
self.assertEqual(message.game.description, 'This is a test game for python-telegram-bot.') bot.leave_chat(-123456)
self.assertEqual(message.game.animation.file_id, 'CgADAQADKwIAAvjAuQABozciVqhFDO0C')
self.assertEqual(message.game.photo[0].file_size, 851)
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def testSendChatAction(self): def test_get_chat(self, bot, group_id):
self._bot.sendChatAction(action=telegram.ChatAction.TYPING, chat_id=self._chat_id) chat = bot.get_chat(group_id)
assert chat.type == 'group'
assert chat.title == '>>> telegram.Bot() - Developers'
assert chat.id == int(group_id)
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def testGetUserProfilePhotos(self): def test_get_chat_administrators(self, bot, channel_id):
upf = self._bot.getUserProfilePhotos(user_id=self._chat_id) admins = bot.get_chat_administrators(channel_id)
assert isinstance(admins, list)
self.assertTrue(self.is_json(upf.to_json()))
self.assertEqual(upf.photos[0][0].file_size, 12421)
@flaky(3, 1)
@timeout(10)
def test_get_one_user_profile_photo(self):
upf = self._bot.getUserProfilePhotos(user_id=self._chat_id, offset=0)
self.assertTrue(self.is_json(upf.to_json()))
self.assertEqual(upf.photos[0][0].file_size, 12421)
def _test_invalid_token(self, token):
self.assertRaisesRegexp(telegram.error.InvalidToken, 'Invalid token', telegram.Bot, token)
def testInvalidToken1(self):
self._test_invalid_token('123')
def testInvalidToken2(self):
self._test_invalid_token('12a:')
def testInvalidToken3(self):
self._test_invalid_token('12:')
def testInvalidToken4(self):
# white spaces are invalid
self._test_invalid_token('1234:abcd1234\n')
self._test_invalid_token(' 1234:abcd1234')
self._test_invalid_token(' 1234:abcd1234\r')
self._test_invalid_token('1234:abcd 1234')
def testUnauthToken(self):
with self.assertRaisesRegexp(telegram.error.Unauthorized, 'Unauthorized'):
bot = telegram.Bot('1234:abcd1234')
bot.getMe()
def testInvalidSrvResp(self):
with self.assertRaisesRegexp(telegram.error.InvalidToken, 'Invalid token'):
# bypass the valid token check
newbot_cls = type(
'NoTokenValidateBot', (telegram.Bot,), dict(_validate_token=lambda x, y: None))
bot = newbot_cls('0xdeadbeef')
bot.base_url = 'https://api.telegram.org/bot{0}'.format('12')
bot.getMe()
@flaky(3, 1)
@timeout(10)
def testLeaveChat(self):
regex = re.compile('chat not found', re.IGNORECASE)
with self.assertRaisesRegexp(telegram.error.BadRequest, regex):
chat = self._bot.leaveChat(-123456)
with self.assertRaisesRegexp(telegram.error.NetworkError, regex):
chat = self._bot.leaveChat(-123456)
@flaky(3, 1)
@timeout(10)
def testGetChat(self):
chat = self._bot.getChat(self._group_id)
self.assertTrue(self.is_json(chat.to_json()))
self.assertEqual(chat.type, "group")
self.assertEqual(chat.title, ">>> telegram.Bot() - Developers")
self.assertEqual(chat.id, int(self._group_id))
@flaky(3, 1)
@timeout(10)
def testGetChatAdministrators(self):
admins = self._bot.getChatAdministrators(self._channel_id)
self.assertTrue(isinstance(admins, list))
self.assertTrue(self.is_json(admins[0].to_json()))
for a in admins: for a in admins:
self.assertTrue(a.status in ("administrator", "creator")) assert a.status in ('administrator', 'creator')
bot = [a.user for a in admins if a.user.id == 133505823][0]
self._testUserEqualsBot(bot)
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def testGetChatMembersCount(self): def test_get_chat_members_count(self, bot, channel_id):
count = self._bot.getChatMembersCount(self._channel_id) count = bot.get_chat_members_count(channel_id)
self.assertTrue(isinstance(count, int)) assert isinstance(count, int)
self.assertTrue(count > 3) assert count > 3
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def testGetChatMember(self): def test_get_chat_member(self, bot, channel_id):
chat_member = self._bot.getChatMember(self._channel_id, 133505823) chat_member = bot.get_chat_member(channel_id, 103246792) # Eldin
bot = chat_member.user
self.assertTrue(self.is_json(chat_member.to_json())) assert chat_member.status == 'administrator'
self.assertEqual(chat_member.status, "administrator") assert chat_member.user.username == 'EchteEldin'
self._testUserEqualsBot(bot)
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_forward_channel_message(self): def test_set_game_score_1(self, bot, chat_id):
text = 'test forward message'
msg = self._bot.sendMessage(self._channel_id, text)
self.assertEqual(text, msg.text)
fwdmsg = msg.forward(self._chat_id)
self.assertEqual(text, fwdmsg.text)
self.assertEqual(fwdmsg.forward_from_message_id, msg.message_id)
# @flaky(20, 1, _stall_retry)
# @timeout(10)
# def test_set_webhook_get_webhook_info(self):
# url = 'https://python-telegram-bot.org/test/webhook'
# max_connections = 7
# allowed_updates = ['message']
# self._bot.set_webhook(url, max_connections=7, allowed_updates=['message'])
# info = self._bot.getWebhookInfo()
# self._bot.delete_webhook()
# self.assertEqual(url, info.url)
# self.assertEqual(max_connections, info.max_connections)
# self.assertListEqual(allowed_updates, info.allowed_updates)
#
# @flaky(20, 1, _stall_retry)
# @timeout(10)
# def test_delete_webhook(self):
# url = 'https://python-telegram-bot.org/test/webhook'
# self._bot.set_webhook(url)
# self._bot.delete_webhook()
# info = self._bot.getWebhookInfo()
# self.assertEqual(info.url, '')
@flaky(3, 1)
@timeout(10)
def test_set_game_score1(self):
# NOTE: numbering of methods assures proper order between test_set_game_scoreX methods # NOTE: numbering of methods assures proper order between test_set_game_scoreX methods
game_short_name = 'python_telegram_bot_test_game' game_short_name = 'python_telegram_bot_test_game'
game = self._bot.sendGame(game_short_name=game_short_name, chat_id=self._chat_id) game = bot.send_game(chat_id, game_short_name)
message = self._bot.set_game_score( message = bot.set_game_score(
user_id=self._chat_id, user_id=chat_id,
score=int(BASE_TIME) - HIGHSCORE_DELTA, score=int(BASE_TIME) - HIGHSCORE_DELTA,
chat_id=game.chat_id, chat_id=game.chat_id,
message_id=game.message_id) message_id=game.message_id)
self.assertTrue(self.is_json(game.to_json())) assert message.game.description == game.game.description
self.assertEqual(message.game.description, game.game.description) assert message.game.animation.file_id == game.game.animation.file_id
self.assertEqual(message.game.animation.file_id, game.game.animation.file_id) assert message.game.photo[0].file_size == game.game.photo[0].file_size
self.assertEqual(message.game.photo[0].file_size, game.game.photo[0].file_size) assert message.game.text != game.game.text
self.assertNotEqual(message.game.text, game.game.text)
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_set_game_score2(self): def test_set_game_score_2(self, bot, chat_id):
# NOTE: numbering of methods assures proper order between test_set_game_scoreX methods # NOTE: numbering of methods assures proper order between test_set_game_scoreX methods
game_short_name = 'python_telegram_bot_test_game' game_short_name = 'python_telegram_bot_test_game'
game = self._bot.sendGame(game_short_name=game_short_name, chat_id=self._chat_id) game = bot.send_game(chat_id, game_short_name)
score = int(BASE_TIME) - HIGHSCORE_DELTA + 1 score = int(BASE_TIME) - HIGHSCORE_DELTA + 1
message = self._bot.set_game_score( message = bot.set_game_score(
user_id=self._chat_id, user_id=chat_id,
score=score, score=score,
chat_id=game.chat_id, chat_id=game.chat_id,
message_id=game.message_id, message_id=game.message_id,
disable_edit_message=True) disable_edit_message=True)
self.assertTrue(self.is_json(game.to_json())) assert message.game.description == game.game.description
self.assertEqual(message.game.description, game.game.description) assert message.game.animation.file_id == game.game.animation.file_id
self.assertEqual(message.game.animation.file_id, game.game.animation.file_id) assert message.game.photo[0].file_size == game.game.photo[0].file_size
self.assertEqual(message.game.photo[0].file_size, game.game.photo[0].file_size) assert message.game.text == game.game.text
self.assertEqual(message.game.text, game.game.text)
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_set_game_score3(self): def test_set_game_score_3(self, bot, chat_id):
# NOTE: numbering of methods assures proper order between test_set_game_scoreX methods # NOTE: numbering of methods assures proper order between test_set_game_scoreX methods
game_short_name = 'python_telegram_bot_test_game' game_short_name = 'python_telegram_bot_test_game'
game = self._bot.sendGame(game_short_name=game_short_name, chat_id=self._chat_id) game = bot.send_game(chat_id, game_short_name)
score = int(BASE_TIME) - HIGHSCORE_DELTA - 1 score = int(BASE_TIME) - HIGHSCORE_DELTA - 1
with self.assertRaises(BadRequest) as cm: with pytest.raises(BadRequest, match='Bot_score_not_modified'):
self._bot.set_game_score( bot.set_game_score(
user_id=self._chat_id, user_id=chat_id,
score=score, score=score,
chat_id=game.chat_id, chat_id=game.chat_id,
message_id=game.message_id) message_id=game.message_id)
self.assertTrue('BOT_SCORE_NOT_MODIFIED' in str(cm.exception.message).upper())
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_set_game_score4(self): def test_set_game_score_4(self, bot, chat_id):
# NOTE: numbering of methods assures proper order between test_set_game_scoreX methods # NOTE: numbering of methods assures proper order between test_set_game_scoreX methods
game_short_name = 'python_telegram_bot_test_game' game_short_name = 'python_telegram_bot_test_game'
game = self._bot.sendGame(game_short_name=game_short_name, chat_id=self._chat_id) game = bot.send_game(chat_id, game_short_name)
score = int(BASE_TIME) - HIGHSCORE_DELTA - 2 score = int(BASE_TIME) - HIGHSCORE_DELTA - 2
message = self._bot.set_game_score( message = bot.set_game_score(
user_id=self._chat_id, user_id=chat_id,
score=score, score=score,
chat_id=game.chat_id, chat_id=game.chat_id,
message_id=game.message_id, message_id=game.message_id,
force=True) force=True)
self.assertTrue(self.is_json(game.to_json())) assert message.game.description == game.game.description
self.assertEqual(message.game.description, game.game.description) assert message.game.animation.file_id == game.game.animation.file_id
self.assertEqual(message.game.animation.file_id, game.game.animation.file_id) assert message.game.photo[0].file_size == game.game.photo[0].file_size
self.assertEqual(message.game.photo[0].file_size, game.game.photo[0].file_size)
# For some reason the returned message does not contain the updated score. need to fetch # For some reason the returned message does not contain the updated score. need to fetch
# the game again... # the game again...
game2 = self._bot.sendGame(game_short_name=game_short_name, chat_id=self._chat_id) game2 = bot.send_game(chat_id, game_short_name)
self.assertIn(str(score), game2.game.text) assert str(score) in game2.game.text
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_set_game_score_too_low_score(self): def test_set_game_score_too_low_score(self, bot, chat_id):
# We need a game to set the score for # We need a game to set the score for
game_short_name = 'python_telegram_bot_test_game' game_short_name = 'python_telegram_bot_test_game'
game = self._bot.sendGame(game_short_name=game_short_name, chat_id=self._chat_id) game = bot.send_game(chat_id, game_short_name)
with self.assertRaises(BadRequest): with pytest.raises(BadRequest):
self._bot.set_game_score( bot.set_game_score(user_id=chat_id, score=100,
user_id=self._chat_id, score=100, chat_id=game.chat_id, message_id=game.message_id) chat_id=game.chat_id, message_id=game.message_id)
def _testUserEqualsBot(self, user):
"""Tests if user is our trusty @PythonTelegramBot."""
self.assertEqual(user.id, 133505823)
self.assertEqual(user.first_name, 'PythonTelegramBot')
self.assertEqual(user.last_name, None)
self.assertEqual(user.username, 'PythonTelegramBot')
self.assertEqual(user.name, '@PythonTelegramBot')
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_info(self): def test_get_game_high_scores(self, bot, chat_id):
# tests the Bot.info decorator and associated funcs # We need a game to get the scores for
self.assertEqual(self._bot.id, 133505823) game_short_name = 'python_telegram_bot_test_game'
self.assertEqual(self._bot.first_name, 'PythonTelegramBot') game = bot.send_game(chat_id, game_short_name)
self.assertEqual(self._bot.last_name, None) high_scores = bot.get_game_high_scores(chat_id, game.chat_id, game.message_id)
self.assertEqual(self._bot.username, 'PythonTelegramBot') # We assume that the other game score tests ran within 20 sec
self.assertEqual(self._bot.name, '@PythonTelegramBot') assert pytest.approx(high_scores[0].score, abs=20) == int(BASE_TIME) - HIGHSCORE_DELTA
# send_invoice is tested in test_invoice
# TODO: Needs improvement. Need incoming shippping queries to test
def test_answer_shipping_query_ok(self, monkeypatch, bot):
# For now just test that our internals pass the correct data
def test(_, url, data, *args, **kwargs):
return data == {'shipping_query_id': 1, 'ok': True,
'shipping_options': [{'title': 'option1',
'prices': [{'label': 'price', 'amount': 100}],
'id': 1}]}
monkeypatch.setattr('telegram.utils.request.Request.post', test)
shipping_options = ShippingOption(1, 'option1', [LabeledPrice('price', 100)])
assert bot.answer_shipping_query(1, True, shipping_options=[shipping_options])
def test_answer_shipping_query_error_message(self, monkeypatch, bot):
# For now just test that our internals pass the correct data
def test(_, url, data, *args, **kwargs):
return data == {'shipping_query_id': 1, 'error_message': 'Not enough fish',
'ok': False}
monkeypatch.setattr('telegram.utils.request.Request.post', test)
assert bot.answer_shipping_query(1, False, error_message='Not enough fish')
def test_answer_shipping_query_errors(self, monkeypatch, bot):
shipping_options = ShippingOption(1, 'option1', [LabeledPrice('price', 100)])
with pytest.raises(TelegramError, match='should not be empty and there should not be'):
bot.answer_shipping_query(1, True, error_message='Not enough fish')
with pytest.raises(TelegramError, match='should not be empty and there should not be'):
bot.answer_shipping_query(1, False)
with pytest.raises(TelegramError, match='should not be empty and there should not be'):
bot.answer_shipping_query(1, False, shipping_options=shipping_options)
with pytest.raises(TelegramError, match='should not be empty and there should not be'):
bot.answer_shipping_query(1, True)
# TODO: Needs improvement. Need incoming pre checkout queries to test
def test_answer_pre_checkout_query_ok(self, monkeypatch, bot):
# For now just test that our internals pass the correct data
def test(_, url, data, *args, **kwargs):
return data == {'pre_checkout_query_id': 1, 'ok': True}
monkeypatch.setattr('telegram.utils.request.Request.post', test)
assert bot.answer_pre_checkout_query(1, True)
def test_answer_pre_checkout_query_error_message(self, monkeypatch, bot):
# For now just test that our internals pass the correct data
def test(_, url, data, *args, **kwargs):
return data == {'pre_checkout_query_id': 1, 'error_message': 'Not enough fish',
'ok': False}
monkeypatch.setattr('telegram.utils.request.Request.post', test)
assert bot.answer_pre_checkout_query(1, False, error_message='Not enough fish')
def test_answer_pre_checkout_query_errors(self, monkeypatch, bot):
with pytest.raises(TelegramError, match='should not be'):
bot.answer_pre_checkout_query(1, True, error_message='Not enough fish')
with pytest.raises(TelegramError, match='should not be empty'):
bot.answer_pre_checkout_query(1, False)
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_send_contact(self): def test_restrict_chat_member(self, bot, channel_id):
# test disabled due to telegram servers annoyances repeatedly returning: # TODO: Add bot to supergroup so this can be tested properly
# "Flood control exceeded. Retry in 2036 seconds" with pytest.raises(BadRequest, match='Method is available only for supergroups'):
return until = datetime.now() + timedelta(seconds=30)
phone = '+3-54-5445445' assert bot.restrict_chat_member(channel_id,
name = 'name' 95205500,
last = 'last' until_date=datetime.now(),
message = self._bot.send_contact(self._chat_id, phone, name, last) can_send_messages=False,
self.assertEqual(phone.replace('-', ''), message.contact.phone_number) can_send_media_messages=False,
self.assertEqual(name, message.contact.first_name) can_send_other_messages=False,
self.assertEqual(last, message.contact.last_name) can_add_web_page_previews=False)
def test_timeout_propagation(self): @flaky(3, 1)
@pytest.mark.timeout(10)
def test_promote_chat_member(self, bot, channel_id):
# TODO: Add bot to supergroup so this can be tested properly / give bot perms
with pytest.raises(BadRequest, match='Chat_admin_required'):
assert bot.promote_chat_member(channel_id,
95205500,
can_change_info=True,
can_post_messages=True,
can_edit_messages=True,
can_delete_messages=True,
can_invite_users=True,
can_restrict_members=True,
can_pin_messages=True,
can_promote_members=True)
@flaky(3, 1)
@pytest.mark.timeout(10)
def test_export_chat_invite_link(self, bot, channel_id):
# Each link is unique apparently
invite_link = bot.export_chat_invite_link(channel_id)
assert isinstance(invite_link, string_types)
assert invite_link != ''
@flaky(3, 1)
@pytest.mark.timeout(10)
def test_delete_chat_photo(self, bot, channel_id):
assert bot.delete_chat_photo(channel_id)
@flaky(3, 1)
@pytest.mark.timeout(10)
def test_set_chat_photo(self, bot, channel_id):
with open('tests/data/telegram_test_channel.jpg', 'rb') as f:
assert bot.set_chat_photo(channel_id, f)
@flaky(3, 1)
@pytest.mark.timeout(10)
def test_set_chat_title(self, bot, channel_id):
assert bot.set_chat_title(channel_id, '>>> telegram.Bot() - Tests')
@flaky(3, 1)
@pytest.mark.timeout(10)
def test_set_chat_description(self, bot, channel_id):
assert bot.set_chat_description(channel_id, 'Time: ' + str(time.time()))
@flaky(3, 1)
@pytest.mark.timeout(10)
def test_error_pin_unpin_message(self, bot, message):
# TODO: Add bot to supergroup so this can be tested properly
with pytest.raises(BadRequest, match='Method is available only for supergroups'):
bot.pin_chat_message(message.chat_id, message.message_id, disable_notification=True)
with pytest.raises(BadRequest, match='Method is available only for supergroups'):
bot.unpin_chat_message(message.chat_id)
# get_sticker_set, upload_sticker_file, create_new_sticker_set, add_sticker_to_set,
# set_sticker_position_in_set and delete_sticker_from_set are tested in the
# test_sticker module.
def test_timeout_propagation(self, monkeypatch, bot, chat_id):
class OkException(Exception): class OkException(Exception):
pass pass
class MockRequest(Request):
def post(self, url, data, timeout=None):
raise OkException(timeout)
_request = self._bot._request
self._bot._request = MockRequest()
timeout = 500 timeout = 500
with self.assertRaises(OkException) as ok: def post(*args, **kwargs):
self._bot.send_photo(self._chat_id, open('tests/data/telegram.jpg'), timeout=timeout) if kwargs.get('timeout') == 500:
self.assertEqual(ok.exception.args[0], timeout) raise OkException
self._bot._request = _request monkeypatch.setattr('telegram.utils.request.Request.post', post)
if __name__ == '__main__': with pytest.raises(OkException):
unittest.main() bot.send_photo(chat_id, open('tests/data/telegram.jpg', 'rb'), timeout=timeout)

View file

@ -1,61 +0,0 @@
#!/usr/bin/env python
"""This module contains an object that represents Tests for Botan analytics integration"""
import sys
import unittest
import os
from flaky import flaky
sys.path.append('.')
from telegram.contrib.botan import Botan
from tests.base import BaseTest
class MessageMock(object):
chat_id = None
def __init__(self, chat_id):
self.chat_id = chat_id
def to_json(self):
return "{}"
@flaky(3, 1)
class BotanTest(BaseTest, unittest.TestCase):
"""This object represents Tests for Botan analytics integration."""
token = os.environ.get('BOTAN_TOKEN')
def test_track(self):
botan = Botan(self.token)
message = MessageMock(self._chat_id)
result = botan.track(message, 'named event')
self.assertTrue(result)
def test_track_fail(self):
botan = Botan(self.token)
botan.url_template = 'https://api.botan.io/traccc?token={token}&uid={uid}&name={name}'
message = MessageMock(self._chat_id)
result = botan.track(message, 'named event')
self.assertFalse(result)
def test_wrong_message(self):
botan = Botan(self.token)
message = MessageMock(self._chat_id)
message = delattr(message, 'chat_id')
result = botan.track(message, 'named event')
self.assertFalse(result)
def test_wrong_endpoint(self):
botan = Botan(self.token)
botan.url_template = 'https://api.botaaaaan.io/traccc?token={token}&uid={uid}&name={name}'
message = MessageMock(self._chat_id)
result = botan.track(message, 'named event')
self.assertFalse(result)
if __name__ == '__main__':
unittest.main()

152
tests/test_callbackquery.py Normal file
View file

@ -0,0 +1,152 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
import pytest
from telegram import CallbackQuery, User, Message, Chat, Audio
@pytest.fixture(scope='class', params=['message', 'inline'])
def callback_query(bot, request):
cbq = CallbackQuery(TestCallbackQuery.id,
TestCallbackQuery.from_user,
TestCallbackQuery.chat_instance,
data=TestCallbackQuery.data,
game_short_name=TestCallbackQuery.game_short_name,
bot=bot)
if request.param == 'message':
cbq.message = TestCallbackQuery.message
else:
cbq.inline_message_id = TestCallbackQuery.inline_message_id
return cbq
class TestCallbackQuery(object):
id = 'id'
from_user = User(1, 'test_user')
chat_instance = 'chat_instance'
message = Message(3, User(5, 'bot'), None, Chat(4, 'private'))
data = 'data'
inline_message_id = 'inline_message_id'
game_short_name = 'the_game'
def test_de_json(self, bot):
json_dict = {'id': self.id,
'from': self.from_user.to_dict(),
'chat_instance': self.chat_instance,
'message': self.message.to_dict(),
'data': self.data,
'inline_message_id': self.inline_message_id,
'game_short_name': self.game_short_name}
callback_query = CallbackQuery.de_json(json_dict, bot)
assert callback_query.id == self.id
assert callback_query.from_user == self.from_user
assert callback_query.chat_instance == self.chat_instance
assert callback_query.message == self.message
assert callback_query.data == self.data
assert callback_query.inline_message_id == self.inline_message_id
assert callback_query.game_short_name == self.game_short_name
def test_to_dict(self, callback_query):
callback_query_dict = callback_query.to_dict()
assert isinstance(callback_query_dict, dict)
assert callback_query_dict['id'] == callback_query.id
assert callback_query_dict['from'] == callback_query.from_user.to_dict()
assert callback_query_dict['chat_instance'] == callback_query.chat_instance
if callback_query.message:
assert callback_query_dict['message'] == callback_query.message.to_dict()
else:
assert callback_query_dict['inline_message_id'] == callback_query.inline_message_id
assert callback_query_dict['data'] == callback_query.data
assert callback_query_dict['game_short_name'] == callback_query.game_short_name
def test_answer(self, monkeypatch, callback_query):
def test(*args, **kwargs):
return args[1] == callback_query.id
monkeypatch.setattr('telegram.Bot.answerCallbackQuery', test)
# TODO: PEP8
assert callback_query.answer()
def test_edit_message_text(self, monkeypatch, callback_query):
def test(*args, **kwargs):
try:
id = kwargs['inline_message_id'] == callback_query.inline_message_id
text = kwargs['text'] == 'test'
return id and text
except KeyError:
chat_id = kwargs['chat_id'] == callback_query.message.chat_id
message_id = kwargs['message_id'] == callback_query.message.message_id
text = kwargs['text'] == 'test'
return chat_id and message_id and text
monkeypatch.setattr('telegram.Bot.edit_message_text', test)
assert callback_query.edit_message_text(text='test')
def test_edit_message_caption(self, monkeypatch, callback_query):
def test(*args, **kwargs):
try:
id = kwargs['inline_message_id'] == callback_query.inline_message_id
caption = kwargs['caption'] == 'new caption'
return id and caption
except KeyError:
id = kwargs['chat_id'] == callback_query.message.chat_id
message = kwargs['message_id'] == callback_query.message.message_id
caption = kwargs['caption'] == 'new caption'
return id and message and caption
monkeypatch.setattr('telegram.Bot.edit_message_caption', test)
assert callback_query.edit_message_caption(caption='new caption')
def test_edit_message_reply_markup(self, monkeypatch, callback_query):
def test(*args, **kwargs):
try:
id = kwargs['inline_message_id'] == callback_query.inline_message_id
reply_markup = kwargs['reply_markup'] == [['1', '2']]
return id and reply_markup
except KeyError:
id = kwargs['chat_id'] == callback_query.message.chat_id
message = kwargs['message_id'] == callback_query.message.message_id
reply_markup = kwargs['reply_markup'] == [['1', '2']]
return id and message and reply_markup
monkeypatch.setattr('telegram.Bot.edit_message_reply_markup', test)
assert callback_query.edit_message_reply_markup(reply_markup=[['1', '2']])
def test_equality(self):
a = CallbackQuery(self.id, self.from_user, 'chat')
b = CallbackQuery(self.id, self.from_user, 'chat')
c = CallbackQuery(self.id, None, '')
d = CallbackQuery('', None, 'chat')
e = Audio(self.id, 1)
assert a == b
assert hash(a) == hash(b)
assert a is not b
assert a == c
assert hash(a) == hash(c)
assert a != d
assert hash(a) != hash(d)
assert a != e
assert hash(a) != hash(e)

View file

@ -0,0 +1,169 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
import pytest
from telegram import (Update, CallbackQuery, Bot, Message, User, Chat, InlineQuery,
ChosenInlineResult, ShippingQuery, PreCheckoutQuery)
from telegram.ext import CallbackQueryHandler
message = Message(1, User(1, ''), None, Chat(1, ''), text='Text')
params = [
{'message': message},
{'edited_message': message},
{'channel_post': message},
{'edited_channel_post': message},
{'inline_query': InlineQuery(1, User(1, ''), '', '')},
{'chosen_inline_result': ChosenInlineResult('id', User(1, ''), '')},
{'shipping_query': ShippingQuery('id', User(1, ''), '', None)},
{'pre_checkout_query': PreCheckoutQuery('id', User(1, ''), '', 0, '')}
]
ids = ('message', 'edited_message', 'channel_post',
'edited_channel_post', 'inline_query', 'chosen_inline_result',
'shipping_query', 'pre_checkout_query')
@pytest.fixture(scope='class', params=params, ids=ids)
def false_update(request):
return Update(update_id=2, **request.param)
@pytest.fixture(scope='function')
def callback_query(bot):
return Update(0, callback_query=CallbackQuery(2, None, None, data='test data'))
class TestCallbackQueryHandler(object):
test_flag = False
@pytest.fixture(autouse=True)
def reset(self):
self.test_flag = False
def callback_basic(self, bot, update):
test_bot = isinstance(bot, Bot)
test_update = isinstance(update, Update)
self.test_flag = test_bot and test_update
def callback_data_1(self, bot, update, user_data=None, chat_data=None):
self.test_flag = (user_data is not None) or (chat_data is not None)
def callback_data_2(self, bot, update, user_data=None, chat_data=None):
self.test_flag = (user_data is not None) and (chat_data is not None)
def callback_queue_1(self, bot, update, job_queue=None, update_queue=None):
self.test_flag = (job_queue is not None) or (update_queue is not None)
def callback_queue_2(self, bot, update, job_queue=None, update_queue=None):
self.test_flag = (job_queue is not None) and (update_queue is not None)
def callback_group(self, bot, update, groups=None, groupdict=None):
if groups is not None:
self.test_flag = groups == ('t', ' data')
if groupdict is not None:
self.test_flag = groupdict == {'begin': 't', 'end': ' data'}
def test_basic(self, dp, callback_query):
handler = CallbackQueryHandler(self.callback_basic)
dp.add_handler(handler)
assert handler.check_update(callback_query)
dp.process_update(callback_query)
assert self.test_flag
def test_with_pattern(self, callback_query):
handler = CallbackQueryHandler(self.callback_basic, pattern='.*est.*')
assert handler.check_update(callback_query)
callback_query.callback_query.data = 'nothing here'
assert not handler.check_update(callback_query)
def test_with_passing_group_dict(self, dp, callback_query):
handler = CallbackQueryHandler(self.callback_group,
pattern='(?P<begin>.*)est(?P<end>.*)',
pass_groups=True)
dp.add_handler(handler)
dp.process_update(callback_query)
assert self.test_flag
dp.remove_handler(handler)
handler = CallbackQueryHandler(self.callback_group,
pattern='(?P<begin>.*)est(?P<end>.*)',
pass_groupdict=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(callback_query)
assert self.test_flag
def test_pass_user_or_chat_data(self, dp, callback_query):
handler = CallbackQueryHandler(self.callback_data_1, pass_user_data=True)
dp.add_handler(handler)
dp.process_update(callback_query)
assert self.test_flag
dp.remove_handler(handler)
handler = CallbackQueryHandler(self.callback_data_1, pass_chat_data=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(callback_query)
assert self.test_flag
dp.remove_handler(handler)
handler = CallbackQueryHandler(self.callback_data_2, pass_chat_data=True,
pass_user_data=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(callback_query)
assert self.test_flag
def test_pass_job_or_update_queue(self, dp, callback_query):
handler = CallbackQueryHandler(self.callback_queue_1, pass_job_queue=True)
dp.add_handler(handler)
dp.process_update(callback_query)
assert self.test_flag
dp.remove_handler(handler)
handler = CallbackQueryHandler(self.callback_queue_1, pass_update_queue=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(callback_query)
assert self.test_flag
dp.remove_handler(handler)
handler = CallbackQueryHandler(self.callback_queue_2, pass_job_queue=True,
pass_update_queue=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(callback_query)
assert self.test_flag
def test_other_update_types(self, false_update):
handler = CallbackQueryHandler(self.callback_basic)
assert not handler.check_update(false_update)

View file

@ -5,106 +5,134 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram Chat"""
import unittest import pytest
import sys
from flaky import flaky from telegram import Chat, ChatAction
from telegram import User
sys.path.append('.')
import telegram
from tests.base import BaseTest
class ChatTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram Chat.""" def chat(bot):
return Chat(TestChat.id, TestChat.title, TestChat.type,
all_members_are_administrators=TestChat.all_members_are_administrators,
bot=bot)
def setUp(self):
self._id = -28767330
self.title = 'ToledosPalaceBot - Group'
self.type = 'group'
self.all_members_are_administrators = False
self.json_dict = { class TestChat(object):
'id': self._id, id = -28767330
'title': self.title, title = 'ToledosPalaceBot - Group'
'type': self.type, type = 'group'
'all_members_are_administrators': self.all_members_are_administrators all_members_are_administrators = False
def test_de_json(self, bot):
json_dict = {
'id': TestChat.id,
'title': TestChat.title,
'type': TestChat.type,
'all_members_are_administrators': TestChat.all_members_are_administrators
} }
chat = Chat.de_json(json_dict, bot)
def test_group_chat_de_json_empty_json(self): assert chat.id == self.id
group_chat = telegram.Chat.de_json({}, self._bot) assert chat.title == self.title
assert chat.type == self.type
assert chat.all_members_are_administrators == self.all_members_are_administrators
self.assertEqual(group_chat, None) def test_to_dict(self, chat):
chat_dict = chat.to_dict()
def test_group_chat_de_json(self): assert isinstance(chat_dict, dict)
group_chat = telegram.Chat.de_json(self.json_dict, self._bot) assert chat_dict['id'] == chat.id
assert chat_dict['title'] == chat.title
assert chat_dict['type'] == chat.type
assert chat_dict['all_members_are_administrators'] == chat.all_members_are_administrators
self.assertEqual(group_chat.id, self._id) def test_send_action(self, monkeypatch, chat):
self.assertEqual(group_chat.title, self.title) def test(*args, **kwargs):
self.assertEqual(group_chat.type, self.type) id = args[1] == chat.id
self.assertEqual(group_chat.all_members_are_administrators, action = kwargs['action'] == ChatAction.TYPING
self.all_members_are_administrators) return id and action
def test_group_chat_to_json(self): monkeypatch.setattr('telegram.Bot.send_chat_action', test)
group_chat = telegram.Chat.de_json(self.json_dict, self._bot) assert chat.send_action(action=ChatAction.TYPING)
self.assertTrue(self.is_json(group_chat.to_json())) def test_leave(self, monkeypatch, chat):
def test(*args, **kwargs):
return args[1] == chat.id
def test_group_chat_to_dict(self): monkeypatch.setattr('telegram.Bot.leave_chat', test)
group_chat = telegram.Chat.de_json(self.json_dict, self._bot) assert chat.leave()
self.assertTrue(self.is_dict(group_chat.to_dict())) def test_get_administrators(self, monkeypatch, chat):
self.assertEqual(group_chat['id'], self._id) def test(*args, **kwargs):
self.assertEqual(group_chat['title'], self.title) return args[1] == chat.id
self.assertEqual(group_chat['type'], self.type)
self.assertEqual(group_chat['all_members_are_administrators'],
self.all_members_are_administrators)
@flaky(3, 1) monkeypatch.setattr('telegram.Bot.get_chat_administrators', test)
def test_send_action(self): assert chat.get_administrators()
"""Test for Chat.send_action"""
self.json_dict['id'] = self._chat_id
group_chat = telegram.Chat.de_json(self.json_dict, self._bot)
group_chat.bot = self._bot
result = group_chat.send_action(telegram.ChatAction.TYPING) def test_get_members_count(self, monkeypatch, chat):
def test(*args, **kwargs):
return args[1] == chat.id
self.assertTrue(result) monkeypatch.setattr('telegram.Bot.get_chat_members_count', test)
assert chat.get_members_count()
def test_get_member(self, monkeypatch, chat):
def test(*args, **kwargs):
chat_id = args[1] == chat.id
user_id = args[2] == 42
return chat_id and user_id
monkeypatch.setattr('telegram.Bot.get_chat_member', test)
assert chat.get_member(42)
def test_kick_member(self, monkeypatch, chat):
def test(*args, **kwargs):
chat_id = args[1] == chat.id
user_id = args[2] == 42
until = kwargs['until_date'] == 43
return chat_id and user_id and until
monkeypatch.setattr('telegram.Bot.kick_chat_member', test)
assert chat.kick_member(42, until_date=43)
def test_unban_member(self, monkeypatch, chat):
def test(*args, **kwargs):
chat_id = args[1] == chat.id
user_id = args[2] == 42
return chat_id and user_id
monkeypatch.setattr('telegram.Bot.unban_chat_member', test)
assert chat.unban_member(42)
def test_equality(self): def test_equality(self):
a = telegram.Chat(self._id, self.title, self.type) a = Chat(self.id, self.title, self.type)
b = telegram.Chat(self._id, self.title, self.type) b = Chat(self.id, self.title, self.type)
c = telegram.Chat(self._id, "", "") c = Chat(self.id, '', '')
d = telegram.Chat(0, self.title, self.type) d = Chat(0, self.title, self.type)
e = telegram.User(self._id, "") e = User(self.id, '')
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertEqual(a, c) assert a == c
self.assertEqual(hash(a), hash(c)) assert hash(a) == hash(c)
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
self.assertNotEqual(a, e) assert a != e
self.assertNotEqual(hash(a), hash(e)) assert hash(a) != hash(e)
if __name__ == '__main__':
unittest.main()

View file

@ -5,67 +5,101 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram ChatMember""" import datetime
import unittest import pytest
import sys
sys.path.append('.') from telegram import User, ChatMember
from telegram.utils.helpers import to_timestamp
import telegram
from tests.base import BaseTest
class ChatMemberTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram ChatMember.""" def user():
return User(1, 'First name')
def setUp(self):
self.user = {'id': 1, 'first_name': 'User'}
self.status = telegram.ChatMember.CREATOR
self.json_dict = {'user': self.user, 'status': self.status} @pytest.fixture(scope='class')
def chat_member(user):
return ChatMember(user, TestChatMember.status)
def test_chatmember_de_json(self):
chatmember = telegram.ChatMember.de_json(self.json_dict, self._bot)
self.assertEqual(chatmember.user.to_dict(), self.user) class TestChatMember(object):
self.assertEqual(chatmember.status, self.status) status = ChatMember.CREATOR
def test_chatmember_to_json(self): def test_de_json_required_args(self, bot, user):
chatmember = telegram.ChatMember.de_json(self.json_dict, self._bot) json_dict = {'user': user.to_dict(), 'status': self.status}
self.assertTrue(self.is_json(chatmember.to_json())) chat_member = ChatMember.de_json(json_dict, bot)
def test_chatmember_to_dict(self): assert chat_member.user == user
chatmember = telegram.ChatMember.de_json(self.json_dict, self._bot) assert chat_member.status == self.status
self.assertTrue(self.is_dict(chatmember.to_dict())) def test_de_json_all_args(self, bot, user):
self.assertEqual(chatmember['user'].to_dict(), self.user) time = datetime.datetime.now()
self.assertEqual(chatmember['status'], self.status) json_dict = {'user': user.to_dict(),
'status': self.status,
'until_date': to_timestamp(time),
'can_be_edited': False,
'can_change_info': True,
'can_post_messages': False,
'can_edit_messages': True,
'can_delete_messages': True,
'can_invite_users': False,
'can_restrict_members': True,
'can_pin_messages': False,
'can_promote_members': True,
'can_send_messages': False,
'can_send_media_messages': True,
'can_send_other_messages': False,
'can_add_web_page_previews': True}
chat_member = ChatMember.de_json(json_dict, bot)
assert chat_member.user == user
assert chat_member.status == self.status
assert chat_member.can_be_edited is False
assert chat_member.can_change_info is True
assert chat_member.can_post_messages is False
assert chat_member.can_edit_messages is True
assert chat_member.can_delete_messages is True
assert chat_member.can_invite_users is False
assert chat_member.can_restrict_members is True
assert chat_member.can_pin_messages is False
assert chat_member.can_promote_members is True
assert chat_member.can_send_messages is False
assert chat_member.can_send_media_messages is True
assert chat_member.can_send_other_messages is False
assert chat_member.can_add_web_page_previews is True
def test_to_dict(self, chat_member):
chat_member_dict = chat_member.to_dict()
assert isinstance(chat_member_dict, dict)
assert chat_member_dict['user'] == chat_member.user.to_dict()
assert chat_member['status'] == chat_member.status
def test_equality(self): def test_equality(self):
a = telegram.ChatMember(telegram.User(1, ""), telegram.ChatMember.ADMINISTRATOR) a = ChatMember(User(1, ''), ChatMember.ADMINISTRATOR)
b = telegram.ChatMember(telegram.User(1, ""), telegram.ChatMember.ADMINISTRATOR) b = ChatMember(User(1, ''), ChatMember.ADMINISTRATOR)
d = telegram.ChatMember(telegram.User(2, ""), telegram.ChatMember.ADMINISTRATOR) d = ChatMember(User(2, ''), ChatMember.ADMINISTRATOR)
d2 = telegram.ChatMember(telegram.User(1, ""), telegram.ChatMember.CREATOR) d2 = ChatMember(User(1, ''), ChatMember.CREATOR)
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
self.assertNotEqual(a, d2) assert a != d2
self.assertNotEqual(hash(a), hash(d2)) assert hash(a) != hash(d2)

View file

@ -5,85 +5,86 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
ChosenInlineResult"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import User, ChosenInlineResult, Location, Voice
import telegram
from tests.base import BaseTest
class ChosenInlineResultTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram ChosenInlineResult.""" def user():
return User(1, 'First name')
def setUp(self):
user = telegram.User(1, 'First name')
self.result_id = 'result id'
self.from_user = user
self.query = 'query text'
self.json_dict = {
'result_id': self.result_id,
'from': self.from_user.to_dict(),
'query': self.query
}
def test_choseninlineresult_de_json(self):
result = telegram.ChosenInlineResult.de_json(self.json_dict, self._bot)
self.assertEqual(result.result_id, self.result_id)
self.assertDictEqual(result.from_user.to_dict(), self.from_user.to_dict())
self.assertEqual(result.query, self.query)
def test_choseninlineresult_to_json(self):
result = telegram.ChosenInlineResult.de_json(self.json_dict, self._bot)
self.assertTrue(self.is_json(result.to_json()))
def test_choseninlineresult_to_dict(self):
result = telegram.ChosenInlineResult.de_json(self.json_dict, self._bot).to_dict()
self.assertTrue(self.is_dict(result))
self.assertEqual(result['result_id'], self.result_id)
self.assertEqual(result['from'], self.from_user.to_dict())
self.assertEqual(result['query'], self.query)
def test_equality(self):
a = telegram.ChosenInlineResult(self.result_id, None, "Query", "")
b = telegram.ChosenInlineResult(self.result_id, None, "Query", "")
c = telegram.ChosenInlineResult(self.result_id, None, "", "")
d = telegram.ChosenInlineResult("", None, "Query", "")
e = telegram.Voice(self.result_id, 0)
self.assertEqual(a, b)
self.assertEqual(hash(a), hash(b))
self.assertIsNot(a, b)
self.assertEqual(a, c)
self.assertEqual(hash(a), hash(c))
self.assertNotEqual(a, d)
self.assertNotEqual(hash(a), hash(d))
self.assertNotEqual(a, e)
self.assertNotEqual(hash(a), hash(e))
if __name__ == '__main__': @pytest.fixture(scope='class')
unittest.main() def chosen_inline_result(user):
return ChosenInlineResult(TestChosenInlineResult.result_id, user, TestChosenInlineResult.query)
class TestChosenInlineResult(object):
result_id = 'result id'
query = 'query text'
def test_de_json_required(self, bot, user):
json_dict = {'result_id': self.result_id,
'from': user.to_dict(),
'query': self.query}
result = ChosenInlineResult.de_json(json_dict, bot)
assert result.result_id == self.result_id
assert result.from_user == user
assert result.query == self.query
def test_de_json_all(self, bot, user):
loc = Location(-42.003, 34.004)
json_dict = {'result_id': self.result_id,
'from': user.to_dict(),
'query': self.query,
'location': loc.to_dict(),
'inline_message_id': 'a random id'}
result = ChosenInlineResult.de_json(json_dict, bot)
assert result.result_id == self.result_id
assert result.from_user == user
assert result.query == self.query
assert result.location == loc
assert result.inline_message_id == 'a random id'
def test_to_dict(self, chosen_inline_result):
chosen_inline_result_dict = chosen_inline_result.to_dict()
assert isinstance(chosen_inline_result_dict, dict)
assert chosen_inline_result_dict['result_id'] == chosen_inline_result.result_id
assert chosen_inline_result_dict['from'] == chosen_inline_result.from_user.to_dict()
assert chosen_inline_result_dict['query'] == chosen_inline_result.query
def test_equality(self, user):
a = ChosenInlineResult(self.result_id, user, 'Query', '')
b = ChosenInlineResult(self.result_id, user, 'Query', '')
c = ChosenInlineResult(self.result_id, user, '', '')
d = ChosenInlineResult('', user, 'Query', '')
e = Voice(self.result_id, 0)
assert a == b
assert hash(a) == hash(b)
assert a is not b
assert a == c
assert hash(a) == hash(c)
assert a != d
assert hash(a) != hash(d)
assert a != e
assert hash(a) != hash(e)

View file

@ -0,0 +1,139 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
import pytest
from telegram import (Update, Chat, Bot, ChosenInlineResult, User, Message, CallbackQuery,
InlineQuery, ShippingQuery, PreCheckoutQuery)
from telegram.ext import ChosenInlineResultHandler
message = Message(1, User(1, ''), None, Chat(1, ''), text='Text')
params = [
{'message': message},
{'edited_message': message},
{'callback_query': CallbackQuery(1, User(1, ''), 'chat', message=message)},
{'channel_post': message},
{'edited_channel_post': message},
{'inline_query': InlineQuery(1, User(1, ''), '', '')},
{'shipping_query': ShippingQuery('id', User(1, ''), '', None)},
{'pre_checkout_query': PreCheckoutQuery('id', User(1, ''), '', 0, '')},
{'callback_query': CallbackQuery(1, User(1, ''), 'chat')}
]
ids = ('message', 'edited_message', 'callback_query', 'channel_post',
'edited_channel_post', 'inline_query',
'shipping_query', 'pre_checkout_query', 'callback_query_without_message')
@pytest.fixture(scope='class', params=params, ids=ids)
def false_update(request):
return Update(update_id=1, **request.param)
@pytest.fixture(scope='class')
def chosen_inline_result():
return Update(1, chosen_inline_result=ChosenInlineResult('result_id',
User(1, 'test_user'),
'query'))
class TestChosenInlineResultHandler(object):
test_flag = False
@pytest.fixture(autouse=True)
def reset(self):
self.test_flag = False
def callback_basic(self, bot, update):
test_bot = isinstance(bot, Bot)
test_update = isinstance(update, Update)
self.test_flag = test_bot and test_update
def callback_data_1(self, bot, update, user_data=None, chat_data=None):
self.test_flag = (user_data is not None) or (chat_data is not None)
def callback_data_2(self, bot, update, user_data=None, chat_data=None):
self.test_flag = (user_data is not None) and (chat_data is not None)
def callback_queue_1(self, bot, update, job_queue=None, update_queue=None):
self.test_flag = (job_queue is not None) or (update_queue is not None)
def callback_queue_2(self, bot, update, job_queue=None, update_queue=None):
self.test_flag = (job_queue is not None) and (update_queue is not None)
def test_basic(self, dp, chosen_inline_result):
handler = ChosenInlineResultHandler(self.callback_basic)
dp.add_handler(handler)
assert handler.check_update(chosen_inline_result)
dp.process_update(chosen_inline_result)
assert self.test_flag
def test_pass_user_or_chat_data(self, dp, chosen_inline_result):
handler = ChosenInlineResultHandler(self.callback_data_1, pass_user_data=True)
dp.add_handler(handler)
dp.process_update(chosen_inline_result)
assert self.test_flag
dp.remove_handler(handler)
handler = ChosenInlineResultHandler(self.callback_data_1, pass_chat_data=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(chosen_inline_result)
assert self.test_flag
dp.remove_handler(handler)
handler = ChosenInlineResultHandler(self.callback_data_2, pass_chat_data=True,
pass_user_data=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(chosen_inline_result)
assert self.test_flag
def test_pass_job_or_update_queue(self, dp, chosen_inline_result):
handler = ChosenInlineResultHandler(self.callback_queue_1, pass_job_queue=True)
dp.add_handler(handler)
dp.process_update(chosen_inline_result)
assert self.test_flag
dp.remove_handler(handler)
handler = ChosenInlineResultHandler(self.callback_queue_1, pass_update_queue=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(chosen_inline_result)
assert self.test_flag
dp.remove_handler(handler)
handler = ChosenInlineResultHandler(self.callback_queue_2, pass_job_queue=True,
pass_update_queue=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(chosen_inline_result)
assert self.test_flag
def test_other_update_types(self, false_update):
handler = ChosenInlineResultHandler(self.callback_basic)
assert not handler.check_update(false_update)

View file

@ -0,0 +1,220 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
import pytest
from telegram import (Message, Update, Chat, Bot, User, CallbackQuery, InlineQuery,
ChosenInlineResult, ShippingQuery, PreCheckoutQuery)
from telegram.ext import CommandHandler, Filters
message = Message(1, User(1, ''), None, Chat(1, ''), text='test')
params = [
{'callback_query': CallbackQuery(1, User(1, ''), 'chat', message=message)},
{'channel_post': message},
{'edited_channel_post': message},
{'inline_query': InlineQuery(1, User(1, ''), '', '')},
{'chosen_inline_result': ChosenInlineResult('id', User(1, ''), '')},
{'shipping_query': ShippingQuery('id', User(1, ''), '', None)},
{'pre_checkout_query': PreCheckoutQuery('id', User(1, ''), '', 0, '')},
{'callback_query': CallbackQuery(1, User(1, ''), 'chat')}
]
ids = ('callback_query', 'channel_post', 'edited_channel_post', 'inline_query',
'chosen_inline_result', 'shipping_query', 'pre_checkout_query',
'callback_query_without_message',)
@pytest.fixture(scope='class', params=params, ids=ids)
def false_update(request):
return Update(update_id=1, **request.param)
@pytest.fixture(scope='function')
def message(bot):
return Message(1, None, None, None, bot=bot)
class TestCommandHandler(object):
test_flag = False
@pytest.fixture(autouse=True)
def reset(self):
self.test_flag = False
def callback_basic(self, bot, update):
test_bot = isinstance(bot, Bot)
test_update = isinstance(update, Update)
self.test_flag = test_bot and test_update
def callback_data_1(self, bot, update, user_data=None, chat_data=None):
self.test_flag = (user_data is not None) or (chat_data is not None)
def callback_data_2(self, bot, update, user_data=None, chat_data=None):
self.test_flag = (user_data is not None) and (chat_data is not None)
def callback_queue_1(self, bot, update, job_queue=None, update_queue=None):
self.test_flag = (job_queue is not None) or (update_queue is not None)
def callback_queue_2(self, bot, update, job_queue=None, update_queue=None):
self.test_flag = (job_queue is not None) and (update_queue is not None)
def ch_callback_args(self, bot, update, args):
if update.message.text == '/test':
self.test_flag = len(args) == 0
elif update.message.text == '/test@{}'.format(bot.username):
self.test_flag = len(args) == 0
else:
self.test_flag = args == ['one', 'two']
def test_basic(self, dp, message):
handler = CommandHandler('test', self.callback_basic)
dp.add_handler(handler)
message.text = '/test'
assert handler.check_update(Update(0, message))
dp.process_update(Update(0, message))
assert self.test_flag
message.text = '/nottest'
assert not handler.check_update(Update(0, message))
message.text = 'test'
assert not handler.check_update(Update(0, message))
message.text = 'not /test at start'
assert not handler.check_update(Update(0, message))
def test_command_list(self, message):
handler = CommandHandler(['test', 'start'], self.callback_basic)
message.text = '/test'
assert handler.check_update(Update(0, message))
message.text = '/start'
assert handler.check_update(Update(0, message))
message.text = '/stop'
assert not handler.check_update(Update(0, message))
def test_edited(self, message):
handler = CommandHandler('test', self.callback_basic, allow_edited=False)
message.text = '/test'
assert handler.check_update(Update(0, message))
assert not handler.check_update(Update(0, edited_message=message))
handler.allow_edited = True
assert handler.check_update(Update(0, message))
assert handler.check_update(Update(0, edited_message=message))
def test_directed_commands(self, message):
handler = CommandHandler('test', self.callback_basic)
message.text = '/test@{}'.format(message.bot.username)
assert handler.check_update(Update(0, message))
message.text = '/test@otherbot'
assert not handler.check_update(Update(0, message))
def test_with_filter(self, message):
handler = CommandHandler('test', self.callback_basic, Filters.group)
message.chat = Chat(-23, 'group')
message.text = '/test'
assert handler.check_update(Update(0, message))
message.chat = Chat(23, 'private')
assert not handler.check_update(Update(0, message))
def test_pass_args(self, dp, message):
handler = CommandHandler('test', self.ch_callback_args, pass_args=True)
dp.add_handler(handler)
message.text = '/test'
dp.process_update(Update(0, message=message))
assert self.test_flag
self.test_flag = False
message.text = '/test@{}'.format(message.bot.username)
dp.process_update(Update(0, message=message))
assert self.test_flag
self.test_flag = False
message.text = '/test one two'
dp.process_update(Update(0, message=message))
assert self.test_flag
self.test_flag = False
message.text = '/test@{} one two'.format(message.bot.username)
dp.process_update(Update(0, message=message))
assert self.test_flag
def test_pass_user_or_chat_data(self, dp, message):
handler = CommandHandler('test', self.callback_data_1, pass_user_data=True)
dp.add_handler(handler)
message.text = '/test'
dp.process_update(Update(0, message=message))
assert self.test_flag
dp.remove_handler(handler)
handler = CommandHandler('test', self.callback_data_1, pass_chat_data=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(Update(0, message=message))
assert self.test_flag
dp.remove_handler(handler)
handler = CommandHandler('test', self.callback_data_2, pass_chat_data=True,
pass_user_data=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(Update(0, message=message))
assert self.test_flag
def test_pass_job_or_update_queue(self, dp, message):
handler = CommandHandler('test', self.callback_queue_1, pass_job_queue=True)
dp.add_handler(handler)
message.text = '/test'
dp.process_update(Update(0, message=message))
assert self.test_flag
dp.remove_handler(handler)
handler = CommandHandler('test', self.callback_queue_1, pass_update_queue=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(Update(0, message=message))
assert self.test_flag
dp.remove_handler(handler)
handler = CommandHandler('test', self.callback_queue_2, pass_job_queue=True,
pass_update_queue=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(Update(0, message=message))
assert self.test_flag
def test_other_update_types(self, false_update):
handler = CommandHandler('test', self.callback_basic)
assert not handler.check_update(false_update)

View file

@ -1,6 +1,8 @@
# python-telegram-bot - a Python interface to the Telegram Bot API #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017 # Copyright (C) 2015-2017
# by the python-telegram-bot contributors <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by # it under the terms of the GNU Lesser Public License as published by
@ -14,60 +16,33 @@
# #
# You should have received a copy of the GNU Lesser Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""Test the Telegram constants.""" import pytest
import sys
import unittest
from flaky import flaky from flaky import flaky
sys.path.append('.') from telegram import constants
import telegram
from telegram.error import BadRequest from telegram.error import BadRequest
from tests.base import BaseTest, timeout
class ConstantsTest(BaseTest, unittest.TestCase): class TestConstants(object):
@flaky(3, 1)
@pytest.mark.timeout(10)
def test_max_message_length(self, bot, chat_id):
bot.send_message(chat_id=chat_id, text='a' * constants.MAX_MESSAGE_LENGTH)
with pytest.raises(BadRequest, message='MAX_MESSAGE_LENGTH is no longer valid',
match='too long'):
bot.send_message(chat_id=chat_id, text='a' * (constants.MAX_MESSAGE_LENGTH + 1))
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def testMaxMessageLength(self): def test_max_caption_length(self, bot, chat_id):
self._bot.sendMessage( good_caption = 'a' * constants.MAX_CAPTION_LENGTH
chat_id=self._chat_id, text='a' * telegram.constants.MAX_MESSAGE_LENGTH) with open('tests/data/telegram.png', 'rb') as f:
good_msg = bot.send_photo(photo=f, caption=good_caption, chat_id=chat_id)
try: assert good_msg.caption == good_caption
self._bot.sendMessage(
chat_id=self._chat_id, text='a' * (telegram.constants.MAX_MESSAGE_LENGTH + 1))
except BadRequest as e:
err = str(e)
self.assertTrue("too long" in err) # BadRequest: 'Message is too long'
@flaky(3, 1)
@timeout(10)
def testMaxCaptionLength(self):
good_caption = 'a' * telegram.constants.MAX_CAPTION_LENGTH
good_msg = self._bot.sendPhoto(
photo=open('tests/data/telegram.png', 'rb'),
caption=good_caption,
chat_id=self._chat_id)
self.assertEqual(good_msg.caption, good_caption)
bad_caption = good_caption + 'Z' bad_caption = good_caption + 'Z'
try: with open('tests/data/telegram.png', 'rb') as f:
bad_msg = self._bot.sendPhoto( bad_message = bot.send_photo(photo=f, caption=bad_caption, chat_id=chat_id)
photo=open('tests/data/telegram.png', 'rb'), assert bad_message.caption != bad_caption
caption='a' * (telegram.constants.MAX_CAPTION_LENGTH + 1), assert len(bad_message.caption) == constants.MAX_CAPTION_LENGTH
chat_id=self._chat_id)
except BadRequest as e:
# This used to be the way long caption was handled before Oct? Nov? 2016
err = str(e)
self.assertTrue("TOO_LONG" in err) # BadRequest: 'MEDIA_CAPTION_TOO_LONG'
else:
self.assertNotEqual(bad_msg.caption, bad_caption)
self.assertEqual(len(bad_msg.caption), telegram.constants.MAX_CAPTION_LENGTH)
if __name__ == '__main__':
unittest.main()

View file

@ -5,108 +5,92 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram Contact"""
import unittest import pytest
import sys
from flaky import flaky from telegram import Contact, Voice
sys.path.append('.')
import telegram
from tests.base import BaseTest
class ContactTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram Contact.""" def contact():
return Contact(TestContact.phone_number, TestContact.first_name, TestContact.last_name,
TestContact.user_id)
def setUp(self):
self.phone_number = '+11234567890'
self.first_name = 'Leandro Toledo'
self.last_name = ''
self.user_id = 0
self.json_dict = { class TestContact(object):
'phone_number': self.phone_number, phone_number = '+11234567890'
'first_name': self.first_name, first_name = 'Leandro'
'last_name': self.last_name, last_name = 'Toledo'
'user_id': self.user_id user_id = 23
}
def test_contact_de_json(self): def test_de_json_required(self, bot):
contact = telegram.Contact.de_json(self.json_dict, self._bot) json_dict = {'phone_number': self.phone_number, 'first_name': self.first_name}
contact = Contact.de_json(json_dict, bot)
self.assertEqual(contact.phone_number, self.phone_number) assert contact.phone_number == self.phone_number
self.assertEqual(contact.first_name, self.first_name) assert contact.first_name == self.first_name
self.assertEqual(contact.last_name, self.last_name)
self.assertEqual(contact.user_id, self.user_id)
'''Commented out because it caused too many "RetryAfter: Flood control exceeded" errors. def test_de_json_all(self, bot):
def test_send_contact_with_contact(self): json_dict = {'phone_number': self.phone_number, 'first_name': self.first_name,
con = telegram.Contact.de_json(self.json_dict, self._bot) 'last_name': self.last_name, 'user_id': self.user_id}
message = self._bot.send_contact(contact=con, chat_id=self._chat_id) contact = Contact.de_json(json_dict, bot)
contact = message.contact
self.assertEqual(contact, con) assert contact.phone_number == self.phone_number
''' assert contact.first_name == self.first_name
assert contact.last_name == self.last_name
assert contact.user_id == self.user_id
def test_contact_to_json(self): def test_send_with_contact(self, monkeypatch, bot, chat_id, contact):
contact = telegram.Contact.de_json(self.json_dict, self._bot) def test(_, url, data, **kwargs):
phone = data['phone_number'] == contact.phone_number
first = data['first_name'] == contact.first_name
last = data['last_name'] == contact.last_name
return phone and first and last
self.assertTrue(self.is_json(contact.to_json())) monkeypatch.setattr('telegram.utils.request.Request.post', test)
message = bot.send_contact(contact=contact, chat_id=chat_id)
assert message
def test_contact_to_dict(self): def test_send_contact_without_required(self, bot, chat_id):
contact = telegram.Contact.de_json(self.json_dict, self._bot) with pytest.raises(ValueError, match='Either contact or phone_number and first_name'):
bot.send_contact(chat_id=chat_id)
self.assertTrue(self.is_dict(contact.to_dict())) def test_to_dict(self, contact):
self.assertEqual(contact['phone_number'], self.phone_number) contact_dict = contact.to_dict()
self.assertEqual(contact['first_name'], self.first_name)
self.assertEqual(contact['last_name'], self.last_name) assert isinstance(contact_dict, dict)
self.assertEqual(contact['user_id'], self.user_id) assert contact_dict['phone_number'] == contact.phone_number
assert contact_dict['first_name'] == contact.first_name
assert contact_dict['last_name'] == contact.last_name
assert contact_dict['user_id'] == contact.user_id
def test_equality(self): def test_equality(self):
a = telegram.Contact(self.phone_number, self.first_name) a = Contact(self.phone_number, self.first_name)
b = telegram.Contact(self.phone_number, self.first_name) b = Contact(self.phone_number, self.first_name)
c = telegram.Contact(self.phone_number, "") c = Contact(self.phone_number, '')
d = telegram.Contact("", self.first_name) d = Contact('', self.first_name)
e = telegram.Voice("", 0) e = Voice('', 0)
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertEqual(a, c) assert a == c
self.assertEqual(hash(a), hash(c)) assert hash(a) == hash(c)
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
self.assertNotEqual(a, e) assert a != e
self.assertNotEqual(hash(a), hash(e)) assert hash(a) != hash(e)
''' Commented out, because it would cause "Too Many Requests (429)" errors.
@flaky(3, 1)
def test_reply_contact(self):
"""Test for Message.reply_contact"""
message = self._bot.sendMessage(self._chat_id, '.')
message = message.reply_contact(self.phone_number, self.first_name)
self.assertEqual(message.contact.phone_number, self.phone_number)
self.assertEqual(message.contact.first_name, self.first_name)
'''
if __name__ == '__main__':
unittest.main()

View file

@ -1,77 +1,60 @@
#!/usr/bin/env python #!/usr/bin/env python
# encoding: utf-8
# #
# A library that provides a Python interface to the Telegram Bot API # A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017 # Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""
This module contains an object that represents Tests for ConversationHandler
"""
import logging
import sys
import unittest
from time import sleep from time import sleep
try: import pytest
# python2
from urllib2 import urlopen, Request, HTTPError
except ImportError:
# python3
from urllib.request import Request, urlopen
from urllib.error import HTTPError
sys.path.append('.') from telegram import Update, Message, User, Chat, CallbackQuery
from telegram.ext import (ConversationHandler, CommandHandler, CallbackQueryHandler)
from telegram import Update, Message, TelegramError, User, Chat, Bot, CallbackQuery
from telegram.ext import (Updater, ConversationHandler, CommandHandler, CallbackQueryHandler,
InlineQueryHandler)
from tests.base import BaseTest
from tests.test_updater import MockBot
# Enable logging
root = logging.getLogger()
root.setLevel(logging.DEBUG)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.WARN)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s ' '- %(message)s')
ch.setFormatter(formatter)
root.addHandler(ch)
class ConversationHandlerTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
""" def user1():
This object represents the tests for the conversation handler. return User(first_name='Misses Test', id=123)
"""
@pytest.fixture(scope='class')
def user2():
return User(first_name='Mister Test', id=124)
class TestConversationHandler(object):
# State definitions # State definitions
# At first we're thirsty. Then we brew coffee, we drink it # At first we're thirsty. Then we brew coffee, we drink it
# and then we can start coding! # and then we can start coding!
END, THIRSTY, BREWING, DRINKING, CODING = range(-1, 4) END, THIRSTY, BREWING, DRINKING, CODING = range(-1, 4)
_updater = None
current_state, entry_points, states, fallbacks = None, None, None, None
group = Chat(0, Chat.GROUP)
second_group = Chat(1, Chat.GROUP)
# Test related # Test related
def setUp(self): @pytest.fixture(autouse=True)
def reset(self):
self.current_state = dict() self.current_state = dict()
self.entry_points = [CommandHandler('start', self.start)] self.entry_points = [CommandHandler('start', self.start)]
self.states = { self.states = {
self.THIRSTY: [CommandHandler('brew', self.brew), CommandHandler('wait', self.start)], self.THIRSTY: [CommandHandler('brew', self.brew), CommandHandler('wait', self.start)],
self.BREWING: [CommandHandler('pourCoffee', self.drink)], self.BREWING: [CommandHandler('pourCoffee', self.drink)],
self.DRINKING: self.DRINKING:
[CommandHandler('startCoding', self.code), CommandHandler('drinkMore', self.drink)], [CommandHandler('startCoding', self.code),
CommandHandler('drinkMore', self.drink)],
self.CODING: [ self.CODING: [
CommandHandler('keepCoding', self.code), CommandHandler('keepCoding', self.code),
CommandHandler('gettingThirsty', self.start), CommandHandler('gettingThirsty', self.start),
@ -80,41 +63,11 @@ class ConversationHandlerTest(BaseTest, unittest.TestCase):
} }
self.fallbacks = [CommandHandler('eat', self.start)] self.fallbacks = [CommandHandler('eat', self.start)]
self.group = Chat(0, Chat.GROUP)
self.second_group = Chat(1, Chat.GROUP)
def _chat(self, user):
return Chat(user.id, Chat.GROUP)
def _setup_updater(self, *args, **kwargs):
self.bot = MockBot(*args, **kwargs)
self.updater = Updater(workers=2, bot=self.bot)
def tearDown(self):
if self.updater is not None:
self.updater.stop()
@property
def updater(self):
return self._updater
@updater.setter
def updater(self, val):
if self._updater:
self._updater.stop()
self._updater = val
def reset(self):
self.current_state = dict()
# State handlers # State handlers
def _set_state(self, update, state): def _set_state(self, update, state):
self.current_state[update.message.from_user.id] = state self.current_state[update.message.from_user.id] = state
return state return state
def _get_state(self, user_id):
return self.current_state[user_id]
# Actions # Actions
def start(self, bot, update): def start(self, bot, update):
return self._set_state(update, self.THIRSTY) return self._set_state(update, self.THIRSTY)
@ -132,116 +85,118 @@ class ConversationHandlerTest(BaseTest, unittest.TestCase):
return self._set_state(update, self.CODING) return self._set_state(update, self.CODING)
# Tests # Tests
def test_addConversationHandler(self): def test_per_all_false(self):
self._setup_updater('', messages=0) with pytest.raises(ValueError, match="can't all be 'False'"):
d = self.updater.dispatcher handler = ConversationHandler(self.entry_points, self.states, self.fallbacks,
user = User(first_name="Misses Test", id=123) per_chat=False, per_user=False, per_message=False)
second_user = User(first_name="Mister Test", id=124)
handler = ConversationHandler( def test_conversation_handler(self, dp, bot, user1, user2):
entry_points=self.entry_points, states=self.states, fallbacks=self.fallbacks) handler = ConversationHandler(entry_points=self.entry_points, states=self.states,
d.add_handler(handler) fallbacks=self.fallbacks)
queue = self.updater.start_polling(0.01) dp.add_handler(handler)
# User one, starts the state machine. # User one, starts the state machine.
message = Message(0, user, None, self.group, text="/start", bot=self.bot) message = Message(0, user1, None, self.group, text='/start', bot=bot)
queue.put(Update(update_id=0, message=message)) dp.process_update(Update(update_id=0, message=message))
sleep(.1) assert self.current_state[user1.id] == self.THIRSTY
self.assertTrue(self.current_state[user.id] == self.THIRSTY)
# The user is thirsty and wants to brew coffee. # The user is thirsty and wants to brew coffee.
message = Message(0, user, None, self.group, text="/brew", bot=self.bot) message.text = '/brew'
queue.put(Update(update_id=0, message=message)) dp.process_update(Update(update_id=0, message=message))
sleep(.1) assert self.current_state[user1.id] == self.BREWING
self.assertTrue(self.current_state[user.id] == self.BREWING)
# Lets see if an invalid command makes sure, no state is changed. # Lets see if an invalid command makes sure, no state is changed.
message = Message(0, user, None, self.group, text="/nothing", bot=self.bot) message.text = '/nothing'
queue.put(Update(update_id=0, message=message)) dp.process_update(Update(update_id=0, message=message))
sleep(.1) assert self.current_state[user1.id] == self.BREWING
self.assertTrue(self.current_state[user.id] == self.BREWING)
# Lets see if the state machine still works by pouring coffee. # Lets see if the state machine still works by pouring coffee.
message = Message(0, user, None, self.group, text="/pourCoffee", bot=self.bot) message.text = '/pourCoffee'
queue.put(Update(update_id=0, message=message)) dp.process_update(Update(update_id=0, message=message))
sleep(.1) assert self.current_state[user1.id] == self.DRINKING
self.assertTrue(self.current_state[user.id] == self.DRINKING)
# Let's now verify that for another user, who did not start yet, # Let's now verify that for another user, who did not start yet,
# the state has not been changed. # the state has not been changed.
message = Message(0, second_user, None, self.group, text="/brew", bot=self.bot) message.from_user = user2
queue.put(Update(update_id=0, message=message)) dp.process_update(Update(update_id=0, message=message))
sleep(.1) with pytest.raises(KeyError):
self.assertRaises(KeyError, self._get_state, user_id=second_user.id) self.current_state[user2.id]
def test_addConversationHandlerPerChat(self): def test_conversation_handler_fallback(self, dp, bot, user1, user2):
self._setup_updater('', messages=0) handler = ConversationHandler(entry_points=self.entry_points, states=self.states,
d = self.updater.dispatcher fallbacks=self.fallbacks)
user = User(first_name="Misses Test", id=123) dp.add_handler(handler)
second_user = User(first_name="Mister Test", id=124)
# first check if fallback will not trigger start when not started
message = Message(0, user1, None, self.group, text='/eat', bot=bot)
dp.process_update(Update(update_id=0, message=message))
with pytest.raises(KeyError):
self.current_state[user1.id]
# User starts the state machine.
message.text = '/start'
dp.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.THIRSTY
# The user is thirsty and wants to brew coffee.
message.text = '/brew'
dp.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.BREWING
# Now a fallback command is issued
message.text = '/eat'
dp.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.THIRSTY
def test_conversation_handler_per_chat(self, dp, bot, user1, user2):
handler = ConversationHandler( handler = ConversationHandler(
entry_points=self.entry_points, entry_points=self.entry_points,
states=self.states, states=self.states,
fallbacks=self.fallbacks, fallbacks=self.fallbacks,
per_user=False) per_user=False)
d.add_handler(handler) dp.add_handler(handler)
queue = self.updater.start_polling(0.01)
# User one, starts the state machine. # User one, starts the state machine.
message = Message(0, user, None, self.group, text="/start", bot=self.bot) message = Message(0, user1, None, self.group, text='/start', bot=bot)
queue.put(Update(update_id=0, message=message)) dp.process_update(Update(update_id=0, message=message))
sleep(.1)
# The user is thirsty and wants to brew coffee. # The user is thirsty and wants to brew coffee.
message = Message(0, user, None, self.group, text="/brew", bot=self.bot) message.text = '/brew'
queue.put(Update(update_id=0, message=message)) dp.process_update(Update(update_id=0, message=message))
sleep(.1)
# Let's now verify that for another user, who did not start yet, # Let's now verify that for another user, who did not start yet,
# the state will be changed because they are in the same group. # the state will be changed because they are in the same group.
message = Message(0, second_user, None, self.group, text="/pourCoffee", bot=self.bot) message.from_user = user2
queue.put(Update(update_id=0, message=message)) message.text = '/pourCoffee'
sleep(.1) dp.process_update(Update(update_id=0, message=message))
self.assertEquals(handler.conversations[(self.group.id,)], self.DRINKING)
def test_addConversationHandlerPerUser(self): assert handler.conversations[(self.group.id,)] == self.DRINKING
self._setup_updater('', messages=0)
d = self.updater.dispatcher
user = User(first_name="Misses Test", id=123)
def test_conversation_handler_per_user(self, dp, bot, user1):
handler = ConversationHandler( handler = ConversationHandler(
entry_points=self.entry_points, entry_points=self.entry_points,
states=self.states, states=self.states,
fallbacks=self.fallbacks, fallbacks=self.fallbacks,
per_chat=False) per_chat=False)
d.add_handler(handler) dp.add_handler(handler)
queue = self.updater.start_polling(0.01)
# User one, starts the state machine. # User one, starts the state machine.
message = Message(0, user, None, self.group, text="/start", bot=self.bot) message = Message(0, user1, None, self.group, text='/start', bot=bot)
queue.put(Update(update_id=0, message=message)) dp.process_update(Update(update_id=0, message=message))
sleep(.1)
# The user is thirsty and wants to brew coffee. # The user is thirsty and wants to brew coffee.
message = Message(0, user, None, self.group, text="/brew", bot=self.bot) message.text = '/brew'
queue.put(Update(update_id=0, message=message)) dp.process_update(Update(update_id=0, message=message))
sleep(.1)
# Let's now verify that for the same user in a different group, the state will still be # Let's now verify that for the same user in a different group, the state will still be
# updated # updated
message = Message(0, user, None, self.second_group, text="/pourCoffee", bot=self.bot) message.chat = self.second_group
queue.put(Update(update_id=0, message=message)) message.text = '/pourCoffee'
sleep(.1) dp.process_update(Update(update_id=0, message=message))
self.assertEquals(handler.conversations[(user.id,)], self.DRINKING) assert handler.conversations[(user1.id,)] == self.DRINKING
def test_addConversationHandlerPerMessage(self):
self._setup_updater('', messages=0)
d = self.updater.dispatcher
user = User(first_name="Misses Test", id=123)
second_user = User(first_name="Mister Test", id=124)
def test_conversation_handler_per_message(self, dp, bot, user1, user2):
def entry(bot, update): def entry(bot, update):
return 1 return 1
@ -257,85 +212,68 @@ class ConversationHandlerTest(BaseTest, unittest.TestCase):
2: [CallbackQueryHandler(two)]}, 2: [CallbackQueryHandler(two)]},
fallbacks=[], fallbacks=[],
per_message=True) per_message=True)
d.add_handler(handler) dp.add_handler(handler)
queue = self.updater.start_polling(0.01)
# User one, starts the state machine. # User one, starts the state machine.
message = Message(0, user, None, self.group, text="msg w/ inlinekeyboard", bot=self.bot) message = Message(0, user1, None, self.group, text='msg w/ inlinekeyboard', bot=bot)
cbq = CallbackQuery(0, user, None, message=message, data='data', bot=self.bot) cbq = CallbackQuery(0, user1, None, message=message, data='data', bot=bot)
queue.put(Update(update_id=0, callback_query=cbq)) dp.process_update(Update(update_id=0, callback_query=cbq))
sleep(.1)
self.assertEquals(handler.conversations[(self.group.id, user.id, message.message_id)], 1)
cbq = CallbackQuery(0, user, None, message=message, data='data', bot=self.bot) assert handler.conversations[(self.group.id, user1.id, message.message_id)] == 1
queue.put(Update(update_id=0, callback_query=cbq))
sleep(.1) dp.process_update(Update(update_id=0, callback_query=cbq))
self.assertEquals(handler.conversations[(self.group.id, user.id, message.message_id)], 2)
assert handler.conversations[(self.group.id, user1.id, message.message_id)] == 2
# Let's now verify that for a different user in the same group, the state will not be # Let's now verify that for a different user in the same group, the state will not be
# updated # updated
cbq = CallbackQuery(0, second_user, None, message=message, data='data', bot=self.bot) cbq.from_user = user2
queue.put(Update(update_id=0, callback_query=cbq)) dp.process_update(Update(update_id=0, callback_query=cbq))
sleep(.1)
self.assertEquals(handler.conversations[(self.group.id, user.id, message.message_id)], 2)
def test_endOnFirstMessage(self): assert handler.conversations[(self.group.id, user1.id, message.message_id)] == 2
self._setup_updater('', messages=0)
d = self.updater.dispatcher
user = User(first_name="Misses Test", id=123)
def test_end_on_first_message(self, dp, bot, user1):
handler = ConversationHandler( handler = ConversationHandler(
entry_points=[CommandHandler('start', self.start_end)], states={}, fallbacks=[]) entry_points=[CommandHandler('start', self.start_end)], states={}, fallbacks=[])
d.add_handler(handler) dp.add_handler(handler)
queue = self.updater.start_polling(0.01)
# User starts the state machine and immediately ends it. # User starts the state machine and immediately ends it.
message = Message(0, user, None, self.group, text="/start", bot=self.bot) message = Message(0, user1, None, self.group, text='/start', bot=bot)
queue.put(Update(update_id=0, message=message)) dp.process_update(Update(update_id=0, message=message))
sleep(.1) assert len(handler.conversations) == 0
self.assertEquals(len(handler.conversations), 0)
def test_endOnFirstMessageAsync(self): def test_end_on_first_message_async(self, dp, bot, user1):
self._setup_updater('', messages=0) start_end_async = (lambda bot, update: dp.run_async(self.start_end, bot, update))
d = self.updater.dispatcher
user = User(first_name="Misses Test", id=123)
start_end_async = (lambda bot, update: d.run_async(self.start_end, bot, update))
handler = ConversationHandler( handler = ConversationHandler(
entry_points=[CommandHandler('start', start_end_async)], states={}, fallbacks=[]) entry_points=[CommandHandler('start', start_end_async)], states={}, fallbacks=[])
d.add_handler(handler) dp.add_handler(handler)
queue = self.updater.start_polling(0.01)
# User starts the state machine with an async function that immediately ends the # User starts the state machine with an async function that immediately ends the
# conversation. Async results are resolved when the users state is queried next time. # conversation. Async results are resolved when the users state is queried next time.
message = Message(0, user, None, self.group, text="/start", bot=self.bot) message = Message(0, user1, None, self.group, text='/start', bot=bot)
queue.put(Update(update_id=0, message=message)) dp.update_queue.put(Update(update_id=0, message=message))
sleep(.1) sleep(.1)
# Assert that the Promise has been accepted as the new state # Assert that the Promise has been accepted as the new state
self.assertEquals(len(handler.conversations), 1) assert len(handler.conversations) == 1
message = Message(0, user, None, self.group, text="resolve promise pls", bot=self.bot) message.text = 'resolve promise pls'
queue.put(Update(update_id=0, message=message)) dp.update_queue.put(Update(update_id=0, message=message))
sleep(.1) sleep(.1)
# Assert that the Promise has been resolved and the conversation ended. # Assert that the Promise has been resolved and the conversation ended.
self.assertEquals(len(handler.conversations), 0) assert len(handler.conversations) == 0
def test_perChatMessageWithoutChat(self): def test_per_chat_message_without_chat(self, bot, user1):
handler = ConversationHandler( handler = ConversationHandler(
entry_points=[CommandHandler('start', self.start_end)], states={}, fallbacks=[]) entry_points=[CommandHandler('start', self.start_end)], states={}, fallbacks=[])
user = User(first_name="Misses Test", id=123) cbq = CallbackQuery(0, user1, None, None, bot=bot)
cbq = CallbackQuery(0, user, None, None)
update = Update(0, callback_query=cbq) update = Update(0, callback_query=cbq)
handler.check_update(update) assert not handler.check_update(update)
def test_channelMessageWithoutChat(self): def test_channel_message_without_chat(self, bot):
handler = ConversationHandler(entry_points=[CommandHandler('start', self.start_end)], states={}, fallbacks=[]) handler = ConversationHandler(entry_points=[CommandHandler('start', self.start_end)],
message = Message(0, None, None, Chat(0, Chat.CHANNEL, "Misses Test")) states={}, fallbacks=[])
message = Message(0, None, None, Chat(0, Chat.CHANNEL, 'Misses Test'), bot=bot)
update = Update(0, message=message) update = Update(0, message=message)
handler.check_update(update) assert not handler.check_update(update)
if __name__ == '__main__':
unittest.main()

227
tests/test_dispatcher.py Normal file
View file

@ -0,0 +1,227 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
from queue import Queue
from threading import current_thread
from time import sleep
import pytest
from telegram import TelegramError, Message, User, Chat, Update
from telegram.ext import MessageHandler, Filters, CommandHandler
from telegram.ext.dispatcher import run_async, Dispatcher, DispatcherHandlerContinue, \
DispatcherHandlerStop
from tests.conftest import create_dp
@pytest.fixture(scope='function')
def dp2(bot):
for dp in create_dp(bot):
yield dp
class TestDispatcher(object):
message_update = Update(1, message=Message(1, User(1, ''), None, Chat(1, ''), text='Text'))
received = None
count = 0
@pytest.fixture(autouse=True)
def reset(self):
self.received = None
self.count = 0
def error_handler(self, bot, update, error):
self.received = error.message
def callback_increase_count(self, bot, update):
self.count += 1
def callback_set_count(self, count):
def callback(bot, update):
self.count = count
return callback
def callback_raise_error(self, bot, update):
raise TelegramError(update.message.text)
def callback_if_not_update_queue(self, bot, update, update_queue=None):
if update_queue is not None:
self.received = update.message
def test_error_handler(self, dp):
dp.add_error_handler(self.error_handler)
error = TelegramError('Unauthorized.')
dp.update_queue.put(error)
sleep(.1)
assert self.received == 'Unauthorized.'
# Remove handler
dp.remove_error_handler(self.error_handler)
self.reset()
dp.update_queue.put(error)
sleep(.1)
assert self.received is None
def test_run_async_multiple(self, bot, dp, dp2):
def get_dispatcher_name(q):
q.put(current_thread().name)
q1 = Queue()
q2 = Queue()
dp.run_async(get_dispatcher_name, q1)
dp2.run_async(get_dispatcher_name, q2)
sleep(.1)
name1 = q1.get()
name2 = q2.get()
assert name1 != name2
def test_multiple_run_async_decorator(self, dp, dp2):
# Make sure we got two dispatchers and that they are not the same
assert isinstance(dp, Dispatcher)
assert isinstance(dp2, Dispatcher)
assert dp is not dp2
@run_async
def must_raise_runtime_error():
pass
with pytest.raises(RuntimeError):
must_raise_runtime_error()
def test_run_async_with_args(self, dp):
dp.add_handler(MessageHandler(Filters.all,
run_async(self.callback_if_not_update_queue),
pass_update_queue=True))
dp.update_queue.put(self.message_update)
sleep(.1)
assert self.received == self.message_update.message
def test_error_in_handler(self, dp):
dp.add_handler(MessageHandler(Filters.all, self.callback_raise_error))
dp.add_error_handler(self.error_handler)
dp.update_queue.put(self.message_update)
sleep(.1)
assert self.received == self.message_update.message.text
def test_add_remove_handler(self, dp):
handler = MessageHandler(Filters.all, self.callback_increase_count)
dp.add_handler(handler)
dp.update_queue.put(self.message_update)
sleep(.1)
assert self.count == 1
dp.remove_handler(handler)
dp.update_queue.put(self.message_update)
assert self.count == 1
def test_add_remove_handler_non_default_group(self, dp):
handler = MessageHandler(Filters.all, self.callback_increase_count)
dp.add_handler(handler, group=2)
with pytest.raises(KeyError):
dp.remove_handler(handler)
dp.remove_handler(handler, group=2)
def test_error_start_twice(self, dp):
assert dp.running
dp.start()
def test_handler_order_in_group(self, dp):
dp.add_handler(MessageHandler(Filters.photo, self.callback_set_count(1)))
dp.add_handler(MessageHandler(Filters.all, self.callback_set_count(2)))
dp.add_handler(MessageHandler(Filters.text, self.callback_set_count(3)))
dp.update_queue.put(self.message_update)
sleep(.1)
assert self.count == 2
def test_groups(self, dp):
dp.add_handler(MessageHandler(Filters.all, self.callback_increase_count))
dp.add_handler(MessageHandler(Filters.all, self.callback_increase_count), group=2)
dp.add_handler(MessageHandler(Filters.all, self.callback_increase_count), group=-1)
dp.update_queue.put(self.message_update)
sleep(.1)
assert self.count == 3
def test_add_handler_errors(self, dp):
handler = 'not a handler'
with pytest.raises(TypeError, match='handler is not an instance of'):
dp.add_handler(handler)
handler = MessageHandler(Filters.photo, self.callback_set_count(1))
with pytest.raises(TypeError, match='group is not int'):
dp.add_handler(handler, 'one')
def test_handler_flow_continue(self, bot, dp):
passed = []
def start1(b, u):
passed.append('start1')
raise DispatcherHandlerContinue
def start2(b, u):
passed.append('start2')
def start3(b, u):
passed.append('start3')
def error(b, u, e):
passed.append('error')
passed.append(e)
update = Update(1, message=Message(1, None, None, None, text='/start', bot=bot))
# If Continue raised next handler should be proceed.
passed = []
dp.add_handler(CommandHandler('start', start1))
dp.add_handler(CommandHandler('start', start2))
dp.process_update(update)
assert passed == ['start1', 'start2']
def test_dispatcher_handler_flow_stop(self, dp, bot):
passed = []
def start1(b, u):
passed.append('start1')
raise DispatcherHandlerStop
def start2(b, u):
passed.append('start2')
def start3(b, u):
passed.append('start3')
def error(b, u, e):
passed.append('error')
passed.append(e)
update = Update(1, message=Message(1, None, None, None, text='/start', bot=bot))
# If Stop raised handlers in other groups should not be called.
passed = []
dp.add_handler(CommandHandler('start', start1), 1)
dp.add_handler(CommandHandler('start', start3), 1)
dp.add_handler(CommandHandler('start', start2), 2)
dp.process_update(update)
assert passed == ['start1']

View file

@ -5,218 +5,175 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram Document"""
import os import os
import unittest
import pytest
from flaky import flaky from flaky import flaky
import telegram from telegram import Document, PhotoSize, TelegramError, Voice
from tests.base import BaseTest, timeout
class DocumentTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='function')
"""This object represents Tests for Telegram Document.""" def document_file():
f = open('tests/data/telegram.png', 'rb')
yield f
f.close()
@classmethod
def setUpClass(cls):
super(DocumentTest, cls).setUpClass()
cls.caption = u'DocumentTest - Caption' @pytest.fixture(scope='class')
cls.document_file_url = 'https://python-telegram-bot.org/static/testfiles/telegram.gif' def document(bot, chat_id):
with open('tests/data/telegram.png', 'rb') as f:
return bot.send_document(chat_id, document=f).document
document_file = open('tests/data/telegram.png', 'rb')
document = cls._bot.send_document(cls._chat_id, document=document_file, timeout=10).document
cls.document = document
# Make sure file has been uploaded. class TestDocument(object):
# Simple assertions PY2 Only caption = 'DocumentTest - Caption'
assert isinstance(cls.document, telegram.Document) document_file_url = 'https://python-telegram-bot.org/static/testfiles/telegram.gif'
assert isinstance(cls.document.file_id, str) file_size = 12948
assert cls.document.file_id is not '' mime_type = 'image/png'
file_name = 'telegram.png'
thumb_file_size = 2364
thumb_width = 90
thumb_heigth = 90
def setUp(self): def test_creation(self, document):
self.document_file = open('tests/data/telegram.png', 'rb') assert isinstance(document, Document)
self.json_dict = { assert isinstance(document.file_id, str)
'file_id': self.document.file_id, assert document.file_id is not ''
'thumb': self.document.thumb.to_dict(),
'file_name': self.document.file_name,
'mime_type': self.document.mime_type,
'file_size': self.document.file_size
}
def test_expected_values(self): def test_expected_values(self, document):
self.assertEqual(self.document.file_size, 12948) assert document.file_size == self.file_size
self.assertEqual(self.document.mime_type, 'image/png') assert document.mime_type == self.mime_type
self.assertEqual(self.document.file_name, 'telegram.png') assert document.file_name == self.file_name
self.assertEqual(self.document.thumb.file_size, 2364) assert document.thumb.file_size == self.thumb_file_size
self.assertEqual(self.document.thumb.width, 90) assert document.thumb.width == self.thumb_width
self.assertEqual(self.document.thumb.height, 90) assert document.thumb.height == self.thumb_heigth
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_send_document_all_args(self): def test_send_all_args(self, bot, chat_id, document_file, document):
message = self._bot.sendDocument(self._chat_id, document=self.document_file, caption=self.caption, message = bot.send_document(chat_id, document=document_file, caption=self.caption,
disable_notification=False) disable_notification=False, filename='telegram_custom.png')
document = message.document assert isinstance(message.document, Document)
assert isinstance(message.document.file_id, str)
self.assertIsInstance(document, telegram.Document) assert message.document.file_id != ''
self.assertIsInstance(document.file_id, str) assert isinstance(message.document.thumb, PhotoSize)
self.assertNotEqual(document.file_id, '') assert message.document.file_name == 'telegram_custom.png'
self.assertTrue(isinstance(document.thumb, telegram.PhotoSize)) assert message.document.mime_type == document.mime_type
self.assertEqual(document.file_name, self.document.file_name) assert message.document.file_size == document.file_size
self.assertEqual(document.mime_type, self.document.mime_type) assert message.document.thumb == document.thumb
self.assertEqual(document.file_size, self.document.file_size) assert message.caption == self.caption
self.assertEqual(document.thumb, self.document.thumb)
self.assertEqual(message.caption, self.caption)
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_get_and_download_document(self): def test_get_and_download(self, bot, document):
new_file = self._bot.getFile(self.document.file_id) new_file = bot.get_file(document.file_id)
self.assertEqual(new_file.file_size, self.document.file_size) assert new_file.file_size == document.file_size
self.assertEqual(new_file.file_id, self.document.file_id) assert new_file.file_id == document.file_id
self.assertTrue(new_file.file_path.startswith('https://')) assert new_file.file_path.startswith('https://')
new_file.download('telegram.png') new_file.download('telegram.png')
self.assertTrue(os.path.isfile('telegram.png')) assert os.path.isfile('telegram.png')
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_send_document_png_file_with_custom_file_name(self): def test_send_url_gif_file(self, bot, chat_id):
message = self._bot.sendDocument( message = bot.send_document(chat_id, self.document_file_url)
self._chat_id, self.document_file, filename='telegram_custom.png')
document = message.document document = message.document
self.assertEqual(document.file_name, 'telegram_custom.png') assert isinstance(document, Document)
assert isinstance(document.file_id, str)
assert document.file_id != ''
assert isinstance(document.thumb, PhotoSize)
assert document.file_name == 'telegram.gif'
assert document.mime_type == 'image/gif'
assert document.file_size == 3878
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_send_document_url_gif_file(self): def test_send_resend(self, bot, chat_id, document):
message = self._bot.sendDocument(self._chat_id, self.document_file_url) message = bot.send_document(chat_id=chat_id, document=document.file_id)
document = message.document assert message.document == document
self.assertIsInstance(document, telegram.Document) def test_send_with_document(self, monkeypatch, bot, chat_id, document):
self.assertIsInstance(document.file_id, str) def test(_, url, data, **kwargs):
self.assertNotEqual(document.file_id, '') return data['document'] == document.file_id
self.assertTrue(isinstance(document.thumb, telegram.PhotoSize))
self.assertEqual(document.file_name, 'telegram.gif') monkeypatch.setattr('telegram.utils.request.Request.post', test)
self.assertEqual(document.mime_type, 'image/gif')
self.assertEqual(document.file_size, 3878) message = bot.send_document(document=document, chat_id=chat_id)
assert message
def test_de_json(self, bot, document):
json_dict = {'file_id': 'not a file id',
'thumb': document.thumb.to_dict(),
'file_name': self.file_name,
'mime_type': self.mime_type,
'file_size': self.file_size
}
test_document = Document.de_json(json_dict, bot)
assert test_document.file_id == 'not a file id'
assert test_document.thumb == document.thumb
assert test_document.file_name == self.file_name
assert test_document.mime_type == self.mime_type
assert test_document.file_size == self.file_size
def test_to_dict(self, document):
document_dict = document.to_dict()
assert isinstance(document_dict, dict)
assert document_dict['file_id'] == document.file_id
assert document_dict['file_name'] == document.file_name
assert document_dict['mime_type'] == document.mime_type
assert document_dict['file_size'] == document.file_size
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_send_document_resend(self): def test_error_send_empty_file(self, bot, chat_id):
message = self._bot.sendDocument(chat_id=self._chat_id, document=self.document.file_id) with open(os.devnull, 'rb') as f:
with pytest.raises(TelegramError):
document = message.document bot.send_document(chat_id=chat_id, document=f)
self.assertEqual(document, self.document)
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_send_document_with_document(self): def test_error_send_empty_file_id(self, bot, chat_id):
message = self._bot.send_document(document=self.document, chat_id=self._chat_id) with pytest.raises(TelegramError):
document = message.document bot.send_document(chat_id=chat_id, document='')
self.assertEqual(document, self.document) def test_error_send_without_required_args(self, bot, chat_id):
with pytest.raises(TypeError):
bot.send_document(chat_id=chat_id)
def test_equality(self, document):
a = Document(document.file_id)
b = Document(document.file_id)
d = Document('')
e = Voice(document.file_id, 0)
def test_document_de_json(self): assert a == b
document = telegram.Document.de_json(self.json_dict, self._bot) assert hash(a) == hash(b)
assert a is not b
self.assertEqual(document, self.document) assert a != d
assert hash(a) != hash(d)
def test_document_to_json(self): assert a != e
self.assertTrue(self.is_json(self.document.to_json())) assert hash(a) != hash(e)
def test_document_to_dict(self):
document = self.document.to_dict()
self.assertTrue(self.is_dict(document))
self.assertEqual(document['file_id'], self.document.file_id)
self.assertEqual(document['file_name'], self.document.file_name)
self.assertEqual(document['mime_type'], self.document.mime_type)
self.assertEqual(document['file_size'], self.document.file_size)
@flaky(3, 1)
@timeout(10)
def test_error_send_document_empty_file(self):
json_dict = self.json_dict
del (json_dict['file_id'])
json_dict['document'] = open(os.devnull, 'rb')
with self.assertRaises(telegram.TelegramError):
self._bot.sendDocument(chat_id=self._chat_id, **json_dict)
@flaky(3, 1)
@timeout(10)
def test_error_send_document_empty_file_id(self):
json_dict = self.json_dict
del (json_dict['file_id'])
json_dict['document'] = ''
with self.assertRaises(telegram.TelegramError):
self._bot.sendDocument(chat_id=self._chat_id, **json_dict)
@flaky(3, 1)
@timeout(10)
def test_error_document_without_required_args(self):
json_dict = self.json_dict
del (json_dict['file_id'])
with self.assertRaises(TypeError): self._bot.sendDocument(chat_id=self._chat_id, **json_dict)
@flaky(3, 1)
@timeout(10)
def test_reply_document(self):
"""Test for Message.reply_document"""
message = self._bot.sendMessage(self._chat_id, '.')
message = message.reply_document(self.document_file)
document = message.document
self.assertIsInstance(document, telegram.Document)
self.assertIsInstance(document.file_id, str)
self.assertNotEqual(document.file_id, '')
self.assertTrue(isinstance(document.thumb, telegram.PhotoSize))
def test_equality(self):
a = telegram.Document(self.document.file_id)
b = telegram.Document(self.document.file_id)
d = telegram.Document("")
e = telegram.Voice(self.document.file_id, 0)
self.assertEqual(a, b)
self.assertEqual(hash(a), hash(b))
self.assertIsNot(a, b)
self.assertNotEqual(a, d)
self.assertNotEqual(hash(a), hash(d))
self.assertNotEqual(a, e)
self.assertNotEqual(hash(a), hash(e))
if __name__ == '__main__':
unittest.main()

View file

@ -5,100 +5,88 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram File"""
import sys import pytest
import unittest from flaky import flaky
import os
sys.path.append('.') from telegram import File, TelegramError, Voice
import telegram
from tests.base import BaseTest
class FileTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram File.""" def file(bot):
return File(TestFile.file_id,
file_path=TestFile.file_path,
file_size=TestFile.file_size,
bot=bot)
def setUp(self):
self.json_dict = { class TestFile(object):
'file_id': "NOTVALIDDONTMATTER", file_id = 'NOTVALIDDOESNOTMATTER'
'file_path': file_path = (
'https://api.telegram.org/file/bot133505823:AAHZFMHno3mzVLErU5b5jJvaeG--qUyLyG0/document/file_3', u'https://api.org/file/bot133505823:AAHZFMHno3mzVLErU5b5jJvaeG--qUyLyG0/document/file_3')
'file_size': 28232 file_size = 28232
def test_de_json(self, bot):
json_dict = {
'file_id': self.file_id,
'file_path': self.file_path,
'file_size': self.file_size
} }
new_file = File.de_json(json_dict, bot)
def test_file_de_json(self): assert new_file.file_id == self.file_id
new_file = telegram.File.de_json(self.json_dict, self._bot) assert new_file.file_path == self.file_path
assert new_file.file_size == self.file_size
self.assertEqual(new_file.file_id, self.json_dict['file_id']) def test_to_dict(self, file):
self.assertEqual(new_file.file_path, self.json_dict['file_path']) file_dict = file.to_dict()
self.assertEqual(new_file.file_size, self.json_dict['file_size'])
def test_file_to_json(self): assert isinstance(file_dict, dict)
new_file = telegram.File.de_json(self.json_dict, self._bot) assert file_dict['file_id'] == file.file_id
assert file_dict['file_path'] == file.file_path
assert file_dict['file_size'] == file.file_size
self.assertTrue(self.is_json(new_file.to_json())) @flaky(3, 1)
@pytest.mark.timeout(10)
def test_error_get_empty_file_id(self, bot):
with pytest.raises(TelegramError):
bot.get_file(file_id='')
def test_file_to_dict(self): def test_download(self, monkeypatch, file):
new_file = telegram.File.de_json(self.json_dict, self._bot).to_dict() def test(*args, **kwargs):
raise TelegramError('test worked')
self.assertTrue(self.is_dict(new_file)) monkeypatch.setattr('telegram.utils.request.Request.download', test)
self.assertEqual(new_file['file_id'], self.json_dict['file_id']) with pytest.raises(TelegramError, match='test worked'):
self.assertEqual(new_file['file_path'], self.json_dict['file_path']) file.download()
self.assertEqual(new_file['file_size'], self.json_dict['file_size'])
def test_error_get_empty_file_id(self): def test_equality(self, bot):
json_dict = self.json_dict a = File(self.file_id, bot)
json_dict['file_id'] = '' b = File(self.file_id, bot)
del (json_dict['file_path']) c = File(self.file_id, None)
del (json_dict['file_size']) d = File('', bot)
e = Voice(self.file_id, 0)
with self.assertRaises(telegram.TelegramError): assert a == b
self._bot.getFile(**json_dict) assert hash(a) == hash(b)
assert a is not b
def test_error_file_without_required_args(self): assert a == c
json_dict = self.json_dict assert hash(a) == hash(c)
del (json_dict['file_id']) assert a != d
del (json_dict['file_path']) assert hash(a) != hash(d)
del (json_dict['file_size'])
with self.assertRaises(TypeError): assert a != e
self._bot.getFile(**json_dict) assert hash(a) != hash(e)
def test_equality(self):
a = telegram.File("DOESNTMATTER", self._bot)
b = telegram.File("DOESNTMATTER", self._bot)
c = telegram.File("DOESNTMATTER", None)
d = telegram.File("DOESNTMATTER2", self._bot)
e = telegram.Voice("DOESNTMATTER", 0)
self.assertEqual(a, b)
self.assertEqual(hash(a), hash(b))
self.assertIsNot(a, b)
self.assertEqual(a, c)
self.assertEqual(hash(a), hash(c))
self.assertNotEqual(a, d)
self.assertNotEqual(hash(a), hash(d))
self.assertNotEqual(a, e)
self.assertNotEqual(hash(a), hash(e))
if __name__ == '__main__':
unittest.main()

View file

@ -5,375 +5,350 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
""" import datetime
This module contains an object that represents Tests for Filters for use with MessageHandler.
"""
import sys import pytest
import unittest
from datetime import datetime
import functools
sys.path.append('.')
from telegram import Message, User, Chat, MessageEntity from telegram import Message, User, Chat, MessageEntity
from telegram.ext import Filters, BaseFilter from telegram.ext import Filters, BaseFilter
from tests.base import BaseTest
class FiltersTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='function')
"""This object represents Tests for MessageHandler.Filters""" def message():
return Message(0, User(0, 'Testuser'), datetime.datetime.now(), Chat(0, 'private'))
def setUp(self):
self.message = Message(0, User(0, "Testuser"), datetime.now(), Chat(0, 'private'))
self.e = functools.partial(MessageEntity, offset=0, length=0)
def test_filters_text(self): @pytest.fixture(scope='function',
self.message.text = 'test' params=MessageEntity.ALL_TYPES)
self.assertTrue(Filters.text(self.message)) def message_entity(request):
self.message.text = '/test' return MessageEntity(request.param, 0, 0, url='', user='')
self.assertFalse(Filters.text(self.message))
def test_filters_command(self):
self.message.text = 'test'
self.assertFalse(Filters.command(self.message))
self.message.text = '/test'
self.assertTrue(Filters.command(self.message))
def test_filters_reply(self): class TestFilters(object):
another_message = Message(1, User(1, "TestOther"), datetime.now(), Chat(0, 'private')) def test_filters_all(self, message):
self.message.text = 'test' assert Filters.all(message)
self.assertFalse(Filters.reply(self.message))
self.message.reply_to_message = another_message
self.assertTrue(Filters.reply(self.message))
def test_filters_audio(self): def test_filters_text(self, message):
self.message.audio = 'test' message.text = 'test'
self.assertTrue(Filters.audio(self.message)) assert Filters.text(message)
self.message.audio = None message.text = '/test'
self.assertFalse(Filters.audio(self.message)) assert not Filters.text(message)
def test_filters_document(self): def test_filters_command(self, message):
self.message.document = 'test' message.text = 'test'
self.assertTrue(Filters.document(self.message)) assert not Filters.command(message)
self.message.document = None message.text = '/test'
self.assertFalse(Filters.document(self.message)) assert Filters.command(message)
def test_filters_photo(self): def test_filters_reply(self, message):
self.message.photo = 'test' another_message = Message(1, User(1, 'TestOther'), datetime.datetime.now(),
self.assertTrue(Filters.photo(self.message)) Chat(0, 'private'))
self.message.photo = None message.text = 'test'
self.assertFalse(Filters.photo(self.message)) assert not Filters.reply(message)
message.reply_to_message = another_message
assert Filters.reply(message)
def test_filters_sticker(self): def test_filters_audio(self, message):
self.message.sticker = 'test' assert not Filters.audio(message)
self.assertTrue(Filters.sticker(self.message)) message.audio = 'test'
self.message.sticker = None assert Filters.audio(message)
self.assertFalse(Filters.sticker(self.message))
def test_filters_video(self): def test_filters_document(self, message):
self.message.video = 'test' assert not Filters.document(message)
self.assertTrue(Filters.video(self.message)) message.document = 'test'
self.message.video = None assert Filters.document(message)
self.assertFalse(Filters.video(self.message))
def test_filters_voice(self): def test_filters_photo(self, message):
self.message.voice = 'test' assert not Filters.photo(message)
self.assertTrue(Filters.voice(self.message)) message.photo = 'test'
self.message.voice = None assert Filters.photo(message)
self.assertFalse(Filters.voice(self.message))
def test_filters_contact(self): def test_filters_sticker(self, message):
self.message.contact = 'test' assert not Filters.sticker(message)
self.assertTrue(Filters.contact(self.message)) message.sticker = 'test'
self.message.contact = None assert Filters.sticker(message)
self.assertFalse(Filters.contact(self.message))
def test_filters_location(self): def test_filters_video(self, message):
self.message.location = 'test' assert not Filters.video(message)
self.assertTrue(Filters.location(self.message)) message.video = 'test'
self.message.location = None assert Filters.video(message)
self.assertFalse(Filters.location(self.message))
def test_filters_venue(self): def test_filters_voice(self, message):
self.message.venue = 'test' assert not Filters.voice(message)
self.assertTrue(Filters.venue(self.message)) message.voice = 'test'
self.message.venue = None assert Filters.voice(message)
self.assertFalse(Filters.venue(self.message))
def test_filters_game(self): def test_filters_contact(self, message):
self.message.game = 'test' assert not Filters.contact(message)
self.assertTrue(Filters.game(self.message)) message.contact = 'test'
self.message.game = None assert Filters.contact(message)
self.assertFalse(Filters.game(self.message))
def test_filters_successful_payment(self): def test_filters_location(self, message):
self.message.successful_payment = 'test' assert not Filters.location(message)
self.assertTrue(Filters.successful_payment(self.message)) message.location = 'test'
self.message.successful_payment = None assert Filters.location(message)
self.assertFalse(Filters.successful_payment(self.message))
def test_filters_invoice(self): def test_filters_venue(self, message):
self.message.invoice = 'test' assert not Filters.venue(message)
self.assertTrue(Filters.invoice(self.message)) message.venue = 'test'
self.message.invoice = None assert Filters.venue(message)
self.assertFalse(Filters.invoice(self.message))
def test_filters_status_update(self): def test_filters_status_update(self, message):
self.assertFalse(Filters.status_update(self.message)) assert not Filters.status_update(message)
self.message.new_chat_members = ['test'] message.new_chat_members = ['test']
self.assertTrue(Filters.status_update(self.message)) assert Filters.status_update(message)
self.assertTrue(Filters.status_update.new_chat_members(self.message)) assert Filters.status_update.new_chat_members(message)
self.message.new_chat_members = None message.new_chat_members = None
self.message.left_chat_member = 'test' message.left_chat_member = 'test'
self.assertTrue(Filters.status_update(self.message)) assert Filters.status_update(message)
self.assertTrue(Filters.status_update.left_chat_member(self.message)) assert Filters.status_update.left_chat_member(message)
self.message.left_chat_member = None message.left_chat_member = None
self.message.new_chat_title = 'test' message.new_chat_title = 'test'
self.assertTrue(Filters.status_update(self.message)) assert Filters.status_update(message)
self.assertTrue(Filters.status_update.new_chat_title(self.message)) assert Filters.status_update.new_chat_title(message)
self.message.new_chat_title = '' message.new_chat_title = ''
self.message.new_chat_photo = 'test' message.new_chat_photo = 'test'
self.assertTrue(Filters.status_update(self.message)) assert Filters.status_update(message)
self.assertTrue(Filters.status_update.new_chat_photo(self.message)) assert Filters.status_update.new_chat_photo(message)
self.message.new_chat_photo = None message.new_chat_photo = None
self.message.delete_chat_photo = True message.delete_chat_photo = True
self.assertTrue(Filters.status_update(self.message)) assert Filters.status_update(message)
self.assertTrue(Filters.status_update.delete_chat_photo(self.message)) assert Filters.status_update.delete_chat_photo(message)
self.message.delete_chat_photo = False message.delete_chat_photo = False
self.message.group_chat_created = True message.group_chat_created = True
self.assertTrue(Filters.status_update(self.message)) assert Filters.status_update(message)
self.assertTrue(Filters.status_update.chat_created(self.message)) assert Filters.status_update.chat_created(message)
self.message.group_chat_created = False message.group_chat_created = False
self.message.supergroup_chat_created = True message.supergroup_chat_created = True
self.assertTrue(Filters.status_update(self.message)) assert Filters.status_update(message)
self.assertTrue(Filters.status_update.chat_created(self.message)) assert Filters.status_update.chat_created(message)
self.message.supergroup_chat_created = False message.supergroup_chat_created = False
self.message.migrate_to_chat_id = 100 message.channel_chat_created = True
self.assertTrue(Filters.status_update(self.message)) assert Filters.status_update(message)
self.assertTrue(Filters.status_update.migrate(self.message)) assert Filters.status_update.chat_created(message)
self.message.migrate_to_chat_id = 0 message.channel_chat_created = False
self.message.migrate_from_chat_id = 100 message.migrate_to_chat_id = 100
self.assertTrue(Filters.status_update(self.message)) assert Filters.status_update(message)
self.assertTrue(Filters.status_update.migrate(self.message)) assert Filters.status_update.migrate(message)
self.message.migrate_from_chat_id = 0 message.migrate_to_chat_id = 0
self.message.channel_chat_created = True message.migrate_from_chat_id = 100
self.assertTrue(Filters.status_update(self.message)) assert Filters.status_update(message)
self.assertTrue(Filters.status_update.chat_created(self.message)) assert Filters.status_update.migrate(message)
self.message.channel_chat_created = False message.migrate_from_chat_id = 0
self.message.pinned_message = 'test' message.pinned_message = 'test'
self.assertTrue(Filters.status_update(self.message)) assert Filters.status_update(message)
self.assertTrue(Filters.status_update.pinned_message(self.message)) assert Filters.status_update.pinned_message(message)
self.message.pinned_message = None message.pinned_message = None
def test_entities_filter(self): def test_filters_forwarded(self, message):
self.message.entities = [self.e(MessageEntity.MENTION)] assert not Filters.forwarded(message)
self.assertTrue(Filters.entity(MessageEntity.MENTION)(self.message)) message.forward_date = 'test'
assert Filters.forwarded(message)
self.message.entities = [] def test_filters_game(self, message):
self.assertFalse(Filters.entity(MessageEntity.MENTION)(self.message)) assert not Filters.game(message)
message.game = 'test'
assert Filters.game(message)
self.message.entities = [self.e(MessageEntity.BOLD)] def test_entities_filter(self, message, message_entity):
self.assertFalse(Filters.entity(MessageEntity.MENTION)(self.message)) message.entities = [message_entity]
assert Filters.entity(message_entity.type)(message)
self.message.entities = [self.e(MessageEntity.BOLD), self.e(MessageEntity.MENTION)] message.entities = []
self.assertTrue(Filters.entity(MessageEntity.MENTION)(self.message)) assert not Filters.entity(MessageEntity.MENTION)(message)
def test_private_filter(self): second = message_entity.to_dict()
self.assertTrue(Filters.private(self.message)) second['type'] = 'bold'
self.message.chat.type = "group" second = MessageEntity.de_json(second, None)
self.assertFalse(Filters.private(self.message)) message.entities = [message_entity, second]
assert Filters.entity(message_entity.type)(message)
def test_group_fileter(self): def test_private_filter(self, message):
self.assertFalse(Filters.group(self.message)) assert Filters.private(message)
self.message.chat.type = "group" message.chat.type = 'group'
self.assertTrue(Filters.group(self.message)) assert not Filters.private(message)
self.message.chat.type = "supergroup"
self.assertTrue(Filters.group(self.message))
def test_filters_chat(self): def test_group_filter(self, message):
with self.assertRaisesRegexp(ValueError, 'chat_id or username'): assert not Filters.group(message)
Filters.chat(chat_id=-1, username='chat') message.chat.type = 'group'
with self.assertRaisesRegexp(ValueError, 'chat_id or username'): assert Filters.group(message)
Filters.chat() message.chat.type = 'supergroup'
assert Filters.group(message)
def test_filters_chat_id(self):
self.assertFalse(Filters.chat(chat_id=-1)(self.message))
self.message.chat.id = -1
self.assertTrue(Filters.chat(chat_id=-1)(self.message))
self.message.chat.id = -2
self.assertTrue(Filters.chat(chat_id=[-1, -2])(self.message))
self.assertFalse(Filters.chat(chat_id=-1)(self.message))
def test_filters_chat_username(self):
self.assertFalse(Filters.chat(username='chat')(self.message))
self.message.chat.username = 'chat'
self.assertTrue(Filters.chat(username='@chat')(self.message))
self.assertTrue(Filters.chat(username='chat')(self.message))
self.assertTrue(Filters.chat(username=['chat1', 'chat', 'chat2'])(self.message))
self.assertFalse(Filters.chat(username=['@chat1', 'chat_2'])(self.message))
def test_filters_user(self): def test_filters_user(self):
with self.assertRaisesRegexp(ValueError, 'user_id or username'): with pytest.raises(ValueError, match='user_id or username'):
Filters.user(user_id=1, username='user') Filters.user(user_id=1, username='user')
with self.assertRaisesRegexp(ValueError, 'user_id or username'): with pytest.raises(ValueError, match='user_id or username'):
Filters.user() Filters.user()
def test_filters_user_id(self): def test_filters_user_id(self, message):
self.assertFalse(Filters.user(user_id=1)(self.message)) assert not Filters.user(user_id=1)(message)
self.message.from_user.id = 1 message.from_user.id = 1
self.assertTrue(Filters.user(user_id=1)(self.message)) assert Filters.user(user_id=1)(message)
self.message.from_user.id = 2 message.from_user.id = 2
self.assertTrue(Filters.user(user_id=[1, 2])(self.message)) assert Filters.user(user_id=[1, 2])(message)
self.assertFalse(Filters.user(user_id=1)(self.message)) assert not Filters.user(user_id=[3, 4])(message)
def test_filters_username(self): def test_filters_username(self, message):
self.assertFalse(Filters.user(username='user')(self.message)) assert not Filters.user(username='user')(message)
self.assertFalse(Filters.user(username='Testuser')(self.message)) assert not Filters.user(username='Testuser')(message)
self.message.from_user.username = 'user' message.from_user.username = 'user'
self.assertTrue(Filters.user(username='@user')(self.message)) assert Filters.user(username='@user')(message)
self.assertTrue(Filters.user(username='user')(self.message)) assert Filters.user(username='user')(message)
self.assertTrue(Filters.user(username=['user1', 'user', 'user2'])(self.message)) assert Filters.user(username=['user1', 'user', 'user2'])(message)
self.assertFalse(Filters.user(username=['@username', '@user_2'])(self.message)) assert not Filters.user(username=['@username', '@user_2'])(message)
def test_and_filters(self): def test_filters_chat(self):
self.message.text = 'test' with pytest.raises(ValueError, match='chat_id or username'):
self.message.forward_date = True Filters.chat(chat_id=-1, username='chat')
self.assertTrue((Filters.text & Filters.forwarded)(self.message)) with pytest.raises(ValueError, match='chat_id or username'):
self.message.text = '/test' Filters.chat()
self.assertFalse((Filters.text & Filters.forwarded)(self.message))
self.message.text = 'test'
self.message.forward_date = None
self.assertFalse((Filters.text & Filters.forwarded)(self.message))
self.message.text = 'test' def test_filters_chat_id(self, message):
self.message.forward_date = True assert not Filters.chat(chat_id=-1)(message)
self.message.entities = [self.e(MessageEntity.MENTION)] message.chat.id = -1
self.assertTrue((Filters.text & Filters.forwarded & Filters.entity(MessageEntity.MENTION))( assert Filters.chat(chat_id=-1)(message)
self.message)) message.chat.id = -2
self.message.entities = [self.e(MessageEntity.BOLD)] assert Filters.chat(chat_id=[-1, -2])(message)
self.assertFalse((Filters.text & Filters.forwarded & Filters.entity(MessageEntity.MENTION) assert not Filters.chat(chat_id=[-3, -4])(message)
)(self.message))
def test_or_filters(self): def test_filters_chat_username(self, message):
self.message.text = 'test' assert not Filters.chat(username='chat')(message)
self.assertTrue((Filters.text | Filters.status_update)(self.message)) message.chat.username = 'chat'
self.message.group_chat_created = True assert Filters.chat(username='@chat')(message)
self.assertTrue((Filters.text | Filters.status_update)(self.message)) assert Filters.chat(username='chat')(message)
self.message.text = None assert Filters.chat(username=['chat1', 'chat', 'chat2'])(message)
self.assertTrue((Filters.text | Filters.status_update)(self.message)) assert not Filters.chat(username=['@chat1', 'chat_2'])(message)
self.message.group_chat_created = False
self.assertFalse((Filters.text | Filters.status_update)(self.message))
def test_and_or_filters(self): def test_filters_invoice(self, message):
self.message.text = 'test' assert not Filters.invoice(message)
self.message.forward_date = True message.invoice = 'test'
self.assertTrue((Filters.text & (Filters.forwarded | Filters.entity(MessageEntity.MENTION)) assert Filters.invoice(message)
)(self.message))
self.message.forward_date = False
self.assertFalse((Filters.text & (Filters.forwarded | Filters.entity(MessageEntity.MENTION)
))(self.message))
self.message.entities = [self.e(MessageEntity.MENTION)]
self.assertTrue((Filters.text & (Filters.forwarded | Filters.entity(MessageEntity.MENTION))
)(self.message))
self.assertEqual( def test_filters_successful_payment(self, message):
str((Filters.text & (Filters.forwarded | Filters.entity(MessageEntity.MENTION)))), assert not Filters.successful_payment(message)
'<Filters.text and <Filters.forwarded or Filters.entity(mention)>>' message.successful_payment = 'test'
) assert Filters.successful_payment(message)
def test_inverted_filters(self): def test_language_filter_single(self, message):
self.message.text = '/test' message.from_user.language_code = 'en_US'
self.assertTrue((Filters.command)(self.message)) assert (Filters.language('en_US'))(message)
self.assertFalse((~Filters.command)(self.message)) assert (Filters.language('en'))(message)
self.message.text = 'test' assert not (Filters.language('en_GB'))(message)
self.assertFalse((Filters.command)(self.message)) assert not (Filters.language('da'))(message)
self.assertTrue((~Filters.command)(self.message)) message.from_user.language_code = 'da'
assert not (Filters.language('en_US'))(message)
assert not (Filters.language('en'))(message)
assert not (Filters.language('en_GB'))(message)
assert (Filters.language('da'))(message)
def test_inverted_and_filters(self): def test_language_filter_multiple(self, message):
self.message.text = '/test' f = Filters.language(['en_US', 'da'])
self.message.forward_date = 1 message.from_user.language_code = 'en_US'
self.assertTrue((Filters.forwarded & Filters.command)(self.message)) assert f(message)
self.assertFalse((~Filters.forwarded & Filters.command)(self.message)) message.from_user.language_code = 'en_GB'
self.assertFalse((Filters.forwarded & ~Filters.command)(self.message)) assert not f(message)
self.assertFalse((~(Filters.forwarded & Filters.command))(self.message)) message.from_user.language_code = 'da'
self.message.forward_date = None assert f(message)
self.assertFalse((Filters.forwarded & Filters.command)(self.message))
self.assertTrue((~Filters.forwarded & Filters.command)(self.message))
self.assertFalse((Filters.forwarded & ~Filters.command)(self.message))
self.assertTrue((~(Filters.forwarded & Filters.command))(self.message))
self.message.text = 'test'
self.assertFalse((Filters.forwarded & Filters.command)(self.message))
self.assertFalse((~Filters.forwarded & Filters.command)(self.message))
self.assertFalse((Filters.forwarded & ~Filters.command)(self.message))
self.assertTrue((~(Filters.forwarded & Filters.command))(self.message))
def test_faulty_custom_filter(self): def test_and_filters(self, message):
message.text = 'test'
message.forward_date = True
assert (Filters.text & Filters.forwarded)(message)
message.text = '/test'
assert not (Filters.text & Filters.forwarded)(message)
message.text = 'test'
message.forward_date = None
assert not (Filters.text & Filters.forwarded)(message)
message.text = 'test'
message.forward_date = True
assert (Filters.text & Filters.forwarded & Filters.private)(message)
def test_or_filters(self, message):
message.text = 'test'
assert (Filters.text | Filters.status_update)(message)
message.group_chat_created = True
assert (Filters.text | Filters.status_update)(message)
message.text = None
assert (Filters.text | Filters.status_update)(message)
message.group_chat_created = False
assert not (Filters.text | Filters.status_update)(message)
def test_and_or_filters(self, message):
message.text = 'test'
message.forward_date = True
assert (Filters.text & (Filters.forwarded | Filters.status_update))(message)
message.forward_date = False
assert not (Filters.text & (Filters.forwarded | Filters.status_update))(message)
message.pinned_message = True
assert (Filters.text & (Filters.forwarded | Filters.status_update)(message))
assert str((Filters.text & (Filters.forwarded | Filters.entity(
MessageEntity.MENTION)))) == '<Filters.text and <Filters.forwarded or ' \
'Filters.entity(mention)>>'
def test_inverted_filters(self, message):
message.text = '/test'
assert Filters.command(message)
assert not (~Filters.command)(message)
message.text = 'test'
assert not Filters.command(message)
assert (~Filters.command)(message)
def test_inverted_and_filters(self, message):
message.text = '/test'
message.forward_date = 1
assert (Filters.forwarded & Filters.command)(message)
assert not (~Filters.forwarded & Filters.command)(message)
assert not (Filters.forwarded & ~Filters.command)(message)
assert not (~(Filters.forwarded & Filters.command))(message)
message.forward_date = None
assert not (Filters.forwarded & Filters.command)(message)
assert (~Filters.forwarded & Filters.command)(message)
assert not (Filters.forwarded & ~Filters.command)(message)
assert (~(Filters.forwarded & Filters.command))(message)
message.text = 'test'
assert not (Filters.forwarded & Filters.command)(message)
assert not (~Filters.forwarded & Filters.command)(message)
assert not (Filters.forwarded & ~Filters.command)(message)
assert (~(Filters.forwarded & Filters.command))(message)
def test_faulty_custom_filter(self, message):
class _CustomFilter(BaseFilter): class _CustomFilter(BaseFilter):
pass pass
custom = _CustomFilter() custom = _CustomFilter()
with self.assertRaises(NotImplementedError): with pytest.raises(NotImplementedError):
(custom & Filters.text)(self.message) (custom & Filters.text)(message)
def test_language_filter_single(self): def test_custom_unnamed_filter(self, message):
self.message.from_user.language_code = 'en_US'
self.assertTrue((Filters.language('en_US'))(self.message))
self.assertTrue((Filters.language('en'))(self.message))
self.assertFalse((Filters.language('en_GB'))(self.message))
self.assertFalse((Filters.language('da'))(self.message))
self.message.from_user.language_code = 'en_GB'
self.assertFalse((Filters.language('en_US'))(self.message))
self.assertTrue((Filters.language('en'))(self.message))
self.assertTrue((Filters.language('en_GB'))(self.message))
self.assertFalse((Filters.language('da'))(self.message))
self.message.from_user.language_code = 'da'
self.assertFalse((Filters.language('en_US'))(self.message))
self.assertFalse((Filters.language('en'))(self.message))
self.assertFalse((Filters.language('en_GB'))(self.message))
self.assertTrue((Filters.language('da'))(self.message))
def test_language_filter_multiple(self):
f = Filters.language(['en_US', 'da'])
self.message.from_user.language_code = 'en_US'
self.assertTrue(f(self.message))
self.message.from_user.language_code = 'en_GB'
self.assertFalse(f(self.message))
self.message.from_user.language_code = 'da'
self.assertTrue(f(self.message))
def test_custom_unnamed_filter(self):
class Unnamed(BaseFilter): class Unnamed(BaseFilter):
def filter(self, message): def filter(self, mes):
return True return True
unnamed = Unnamed() unnamed = Unnamed()
self.assertEqual(str(unnamed), Unnamed.__name__) assert str(unnamed) == Unnamed.__name__
if __name__ == '__main__':
unittest.main()

View file

@ -1,76 +1,48 @@
#!/usr/bin/env python #!/usr/bin/env python
# encoding: utf-8
# #
# A library that provides a Python interface to the Telegram Bot API # A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017 # Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram ForceReply"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import ForceReply
import telegram
from tests.base import BaseTest
class ForceReplyTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram ForceReply.""" def force_reply():
return ForceReply(TestForceReply.force_reply, TestForceReply.selective)
def setUp(self):
self.force_reply = True
self.selective = True
self.json_dict = {
'force_reply': self.force_reply,
'selective': self.selective,
}
def test_send_message_with_force_reply(self):
message = self._bot.sendMessage(
self._chat_id,
'Моё судно на воздушной подушке полно угрей',
reply_markup=telegram.ForceReply.de_json(self.json_dict, self._bot))
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(message.text, u'Моё судно на воздушной подушке полно угрей')
def test_force_reply_de_json(self):
force_reply = telegram.ForceReply.de_json(self.json_dict, self._bot)
self.assertEqual(force_reply.force_reply, self.force_reply)
self.assertEqual(force_reply.selective, self.selective)
def test_force_reply_de_json_empty(self):
force_reply = telegram.ForceReply.de_json(None, self._bot)
self.assertFalse(force_reply)
def test_force_reply_to_json(self):
force_reply = telegram.ForceReply.de_json(self.json_dict, self._bot)
self.assertTrue(self.is_json(force_reply.to_json()))
def test_force_reply_to_dict(self):
force_reply = telegram.ForceReply.de_json(self.json_dict, self._bot)
self.assertEqual(force_reply['force_reply'], self.force_reply)
self.assertEqual(force_reply['selective'], self.selective)
if __name__ == '__main__': class TestForceReply(object):
unittest.main() force_reply = True
selective = True
def test_send_message_with_force_reply(self, bot, chat_id, force_reply):
message = bot.send_message(chat_id, 'text', reply_markup=force_reply)
assert message.text == 'text'
def test_expected(self, force_reply):
assert force_reply.force_reply == self.force_reply
assert force_reply.selective == self.selective
def test_to_dict(self, force_reply):
force_reply_dict = force_reply.to_dict()
assert isinstance(force_reply_dict, dict)
assert force_reply_dict['force_reply'] == force_reply.force_reply
assert force_reply_dict['selective'] == force_reply.selective

View file

@ -1,101 +1,97 @@
#!/usr/bin/env python #!/usr/bin/env python
# encoding: utf-8
# #
# A library that provides a Python interface to the Telegram Bot API # A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017 # Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram Games"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import MessageEntity, Game, PhotoSize, Animation
import telegram
from tests.base import BaseTest
class GameTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='function')
"""This object represents Tests for Telegram Game.""" def game():
return Game(TestGame.title,
TestGame.description,
TestGame.photo,
text=TestGame.text,
text_entities=TestGame.text_entities,
animation=TestGame.animation)
def setUp(self):
self.title = 'Python-telegram-bot Test Game'
self.description = 'description'
self.photo = [{'width': 640, 'height': 360, 'file_id': 'Blah', 'file_size': 0}]
self.text = 'Other description'
self.text_entities = [{'offset': 13, 'length': 17, 'type': telegram.MessageEntity.URL}]
self.animation = {'file_id': 'Blah'}
self.json_dict = { class TestGame(object):
title = 'Python-telegram-bot Test Game'
description = 'description'
photo = [PhotoSize('Blah', 640, 360, file_size=0)]
text = (b'\\U0001f469\\u200d\\U0001f469\\u200d\\U0001f467'
b'\\u200d\\U0001f467\\U0001f431http://google.com').decode('unicode-escape')
text_entities = [MessageEntity(13, 17, MessageEntity.URL)]
animation = Animation('blah')
def test_de_json_required(self, bot):
json_dict = {
'title': self.title, 'title': self.title,
'description': self.description, 'description': self.description,
'photo': self.photo, 'photo': [self.photo[0].to_dict()],
'text': self.text,
'text_entities': self.text_entities,
'animation': self.animation
} }
game = Game.de_json(json_dict, bot)
def test_game_de_json(self): assert game.title == self.title
game = telegram.Game.de_json(self.json_dict, self._bot) assert game.description == self.description
assert game.photo == self.photo
self.assertEqual(game.title, self.title) def test_de_json_all(self, bot):
self.assertEqual(game.description, self.description) json_dict = {
self.assertTrue(isinstance(game.photo[0], telegram.PhotoSize)) 'title': self.title,
self.assertEqual(game.text, self.text) 'description': self.description,
self.assertTrue(isinstance(game.text_entities[0], telegram.MessageEntity)) 'photo': [self.photo[0].to_dict()],
self.assertTrue(isinstance(game.animation, telegram.Animation)) 'text': self.text,
'text_entities': [self.text_entities[0].to_dict()],
'animation': self.animation.to_dict()
}
game = Game.de_json(json_dict, bot)
def test_game_to_json(self): assert game.title == self.title
game = telegram.Game.de_json(self.json_dict, self._bot) assert game.description == self.description
assert game.photo == self.photo
assert game.text == self.text
assert game.text_entities == self.text_entities
assert game.animation == self.animation
self.assertTrue(self.is_json(game.to_json())) def test_to_dict(self, game):
game_dict = game.to_dict()
def test_game_all_args(self): assert isinstance(game_dict, dict)
game = telegram.Game( assert game_dict['title'] == game.title
title=self.title, assert game_dict['description'] == game.description
description=self.description, assert game_dict['photo'] == [game.photo[0].to_dict()]
photo=self.photo, assert game_dict['text'] == game.text
text=self.text, assert game_dict['text_entities'] == [game.text_entities[0].to_dict()]
text_entities=self.text_entities, assert game_dict['animation'] == game.animation.to_dict()
animation=self.animation)
self.assertEqual(game.title, self.title) def test_parse_entity(self, game):
self.assertEqual(game.description, self.description) entity = MessageEntity(type=MessageEntity.URL, offset=13, length=17)
self.assertEqual(game.photo, self.photo) game.text_entities = [entity]
self.assertEqual(game.text, self.text)
self.assertEqual(game.text_entities, self.text_entities)
self.assertEqual(game.animation, self.animation)
def test_parse_entity(self): assert game.parse_text_entity(entity) == 'http://google.com'
text = (b'\\U0001f469\\u200d\\U0001f469\\u200d\\U0001f467'
b'\\u200d\\U0001f467\\U0001f431http://google.com').decode('unicode-escape')
entity = telegram.MessageEntity(type=telegram.MessageEntity.URL, offset=13, length=17)
game = telegram.Game(
self.title, self.description, self.photo, text=text, text_entities=[entity])
self.assertEqual(game.parse_text_entity(entity), 'http://google.com')
def test_parse_entities(self): def test_parse_entities(self, game):
text = (b'\\U0001f469\\u200d\\U0001f469\\u200d\\U0001f467' entity = MessageEntity(type=MessageEntity.URL, offset=13, length=17)
b'\\u200d\\U0001f467\\U0001f431http://google.com').decode('unicode-escape') entity_2 = MessageEntity(type=MessageEntity.BOLD, offset=13, length=1)
entity = telegram.MessageEntity(type=telegram.MessageEntity.URL, offset=13, length=17) game.text_entities = [entity_2, entity]
entity_2 = telegram.MessageEntity(type=telegram.MessageEntity.BOLD, offset=13, length=1)
game = telegram.Game( assert game.parse_text_entities(MessageEntity.URL) == {entity: 'http://google.com'}
self.title, self.description, self.photo, text=text, text_entities=[entity_2, entity]) assert game.parse_text_entities() == {entity: 'http://google.com', entity_2: 'h'}
self.assertDictEqual(
game.parse_text_entities(telegram.MessageEntity.URL), {entity: 'http://google.com'})
self.assertDictEqual(game.parse_text_entities(),
{entity: 'http://google.com',
entity_2: 'h'})

View file

@ -0,0 +1,53 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
import pytest
from telegram import GameHighScore, User
@pytest.fixture(scope='class')
def game_highscore():
return GameHighScore(TestGameHighScore.position,
TestGameHighScore.user,
TestGameHighScore.score)
class TestGameHighScore(object):
position = 12
user = User(2, 'test user')
score = 42
def test_de_json(self, bot):
json_dict = {'position': self.position,
'user': self.user.to_dict(),
'score': self.score}
highscore = GameHighScore.de_json(json_dict, bot)
assert highscore.position == self.position
assert highscore.user == self.user
assert highscore.score == self.score
def test_to_dict(self, game_highscore):
game_highscore_dict = game_highscore.to_dict()
assert isinstance(game_highscore_dict, dict)
assert game_highscore_dict['position'] == game_highscore.position
assert game_highscore_dict['user'] == game_highscore.user.to_dict()
assert game_highscore_dict['score'] == game_highscore.score

View file

@ -5,38 +5,24 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
MessageEntity"""
import sys
import unittest
from telegram.utils import helpers from telegram.utils import helpers
sys.path.append('.')
from tests.base import BaseTest
class HelpersTest(BaseTest, unittest.TestCase):
"""This object represents Tests for the Helpers Module"""
class TestHelpers(object):
def test_escape_markdown(self): def test_escape_markdown(self):
test_str = "*bold*, _italic_, `code`, [text_link](http://github.com/)" test_str = '*bold*, _italic_, `code`, [text_link](http://github.com/)'
expected_str = "\*bold\*, \_italic\_, \`code\`, \[text\_link](http://github.com/)" expected_str = '\*bold\*, \_italic\_, \`code\`, \[text\_link](http://github.com/)'
self.assertEquals(expected_str, helpers.escape_markdown(test_str))
assert expected_str == helpers.escape_markdown(test_str)
if __name__ == '__main__':
unittest.main()

View file

@ -1,79 +1,86 @@
#!/usr/bin/env python #!/usr/bin/env python
# encoding: utf-8
# #
# A library that provides a Python interface to the Telegram Bot API # A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017 # Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram InlineKeyboardButton"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import InlineKeyboardButton
import telegram
from tests.base import BaseTest
class InlineKeyboardButtonTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram KeyboardButton.""" def inline_keyboard_button():
return InlineKeyboardButton(TestInlineKeyboardButton.text,
url=TestInlineKeyboardButton.url,
callback_data=TestInlineKeyboardButton.callback_data,
switch_inline_query=TestInlineKeyboardButton.switch_inline_query,
switch_inline_query_current_chat=TestInlineKeyboardButton
.switch_inline_query_current_chat,
callback_game=TestInlineKeyboardButton.callback_game,
pay=TestInlineKeyboardButton.pay)
def setUp(self):
self.text = 'text'
self.url = 'url'
self.callback_data = 'callback data'
self.switch_inline_query = ''
self.json_dict = { class TestInlineKeyboardButton(object):
text = 'text'
url = 'url'
callback_data = 'callback data'
switch_inline_query = 'switch_inline_query'
switch_inline_query_current_chat = 'switch_inline_query_current_chat'
callback_game = 'callback_game'
pay = 'pay'
def test_de_json(self, bot):
json_dict = {
'text': self.text, 'text': self.text,
'url': self.url, 'url': self.url,
'callback_data': self.callback_data, 'callback_data': self.callback_data,
'switch_inline_query': self.switch_inline_query 'switch_inline_query': self.switch_inline_query,
'switch_inline_query_current_chat':
self.switch_inline_query_current_chat,
'callback_game': self.callback_game,
'pay': self.pay
} }
inline_keyboard_button = InlineKeyboardButton.de_json(json_dict, bot)
def test_inline_keyboard_button_de_json(self): assert inline_keyboard_button.text == self.text
inline_keyboard_button = telegram.InlineKeyboardButton.de_json(self.json_dict, self._bot) assert inline_keyboard_button.url == self.url
assert inline_keyboard_button.callback_data == self.callback_data
assert inline_keyboard_button.switch_inline_query == self.switch_inline_query
assert inline_keyboard_button.switch_inline_query_current_chat == \
self.switch_inline_query_current_chat
assert inline_keyboard_button.callback_game == self.callback_game
assert inline_keyboard_button.pay == self.pay
self.assertEqual(inline_keyboard_button.text, self.text) def test_de_list(self, bot, inline_keyboard_button):
self.assertEqual(inline_keyboard_button.url, self.url) keyboard_json = [inline_keyboard_button.to_dict(), inline_keyboard_button.to_dict()]
self.assertEqual(inline_keyboard_button.callback_data, self.callback_data) inline_keyboard_buttons = InlineKeyboardButton.de_list(keyboard_json, bot)
self.assertEqual(inline_keyboard_button.switch_inline_query, self.switch_inline_query)
def test_inline_keyboard_button_de_json_empty(self): assert inline_keyboard_buttons == [inline_keyboard_button, inline_keyboard_button]
inline_keyboard_button = telegram.InlineKeyboardButton.de_json(None, self._bot)
self.assertFalse(inline_keyboard_button) def test_to_dict(self, inline_keyboard_button):
inline_keyboard_button_dict = inline_keyboard_button.to_dict()
def test_inline_keyboard_button_de_list_empty(self): assert isinstance(inline_keyboard_button_dict, dict)
inline_keyboard_button = telegram.InlineKeyboardButton.de_list(None, self._bot) assert inline_keyboard_button_dict['text'] == inline_keyboard_button.text
assert inline_keyboard_button_dict['url'] == inline_keyboard_button.url
self.assertFalse(inline_keyboard_button) assert inline_keyboard_button_dict['callback_data'] == inline_keyboard_button.callback_data
assert inline_keyboard_button_dict['switch_inline_query'] == \
def test_inline_keyboard_button_to_json(self): inline_keyboard_button.switch_inline_query
inline_keyboard_button = telegram.InlineKeyboardButton.de_json(self.json_dict, self._bot) assert inline_keyboard_button_dict['switch_inline_query_current_chat'] == \
inline_keyboard_button.switch_inline_query_current_chat
self.assertTrue(self.is_json(inline_keyboard_button.to_json())) assert inline_keyboard_button_dict['callback_game'] == inline_keyboard_button.callback_game
assert inline_keyboard_button_dict['pay'] == inline_keyboard_button.pay
def test_inline_keyboard_button_to_dict(self):
inline_keyboard_button = telegram.InlineKeyboardButton.de_json(self.json_dict,
self._bot).to_dict()
self.assertTrue(self.is_dict(inline_keyboard_button))
self.assertDictEqual(self.json_dict, inline_keyboard_button)
if __name__ == '__main__':
unittest.main()

View file

@ -1,83 +1,64 @@
#!/usr/bin/env python #!/usr/bin/env python
# encoding: utf-8
# #
# A library that provides a Python interface to the Telegram Bot API # A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017 # Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram InlineKeyboardMarkup"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import InlineKeyboardButton, InlineKeyboardMarkup
import telegram
from tests.base import BaseTest
class InlineKeyboardMarkupTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram KeyboardButton.""" def inline_keyboard_markup():
return InlineKeyboardMarkup(TestInlineKeyboardMarkup.inline_keyboard)
def setUp(self):
self.inline_keyboard = [[ class TestInlineKeyboardMarkup(object):
telegram.InlineKeyboardButton( inline_keyboard = [[
text='button1', callback_data='data1'), telegram.InlineKeyboardButton( InlineKeyboardButton(text='button1', callback_data='data1'),
text='button2', callback_data='data2') InlineKeyboardButton(text='button2', callback_data='data2')
]] ]]
self.json_dict = { def test_send_message_with_inline_keyboard_markup(self, bot, chat_id, inline_keyboard_markup):
'inline_keyboard': message = bot.send_message(
[[self.inline_keyboard[0][0].to_dict(), self.inline_keyboard[0][1].to_dict()]], chat_id,
}
def test_send_message_with_inline_keyboard_markup(self):
message = self._bot.sendMessage(
self._chat_id,
'Testing InlineKeyboardMarkup', 'Testing InlineKeyboardMarkup',
reply_markup=telegram.InlineKeyboardMarkup(self.inline_keyboard)) reply_markup=inline_keyboard_markup)
self.assertTrue(self.is_json(message.to_json())) assert message.text == 'Testing InlineKeyboardMarkup'
self.assertEqual(message.text, 'Testing InlineKeyboardMarkup')
def test_inline_keyboard_markup_de_json_empty(self): def test_de_json(self, bot, inline_keyboard_markup):
inline_keyboard_markup = telegram.InlineKeyboardMarkup.de_json(None, self._bot) json_dict = {
'inline_keyboard': [[
self.inline_keyboard[0][0].to_dict(),
self.inline_keyboard[0][1].to_dict()
]],
}
inline_keyboard_markup_json = InlineKeyboardMarkup.de_json(json_dict, bot)
self.assertFalse(inline_keyboard_markup) assert inline_keyboard_markup_json.to_dict() == inline_keyboard_markup.to_dict()
def test_inline_keyboard_markup_de_json(self): def test_to_dict(self, inline_keyboard_markup):
inline_keyboard_markup = telegram.InlineKeyboardMarkup.de_json(self.json_dict, self._bot) inline_keyboard_markup_dict = inline_keyboard_markup.to_dict()
self.assertTrue(isinstance(inline_keyboard_markup.inline_keyboard, list)) assert isinstance(inline_keyboard_markup_dict, dict)
self.assertTrue( assert inline_keyboard_markup_dict['inline_keyboard'] == [
isinstance(inline_keyboard_markup.inline_keyboard[0][0], [
telegram.InlineKeyboardButton)) self.inline_keyboard[0][0].to_dict(),
self.inline_keyboard[0][1].to_dict()
def test_inline_keyboard_markup_to_json(self): ]
inline_keyboard_markup = telegram.InlineKeyboardMarkup.de_json(self.json_dict, self._bot) ]
self.assertTrue(self.is_json(inline_keyboard_markup.to_json()))
def test_inline_keyboard_markup_to_dict(self):
inline_keyboard_markup = telegram.InlineKeyboardMarkup.de_json(self.json_dict, self._bot)
self.assertTrue(isinstance(inline_keyboard_markup.inline_keyboard, list))
self.assertTrue(
isinstance(inline_keyboard_markup.inline_keyboard[0][0],
telegram.InlineKeyboardButton))
if __name__ == '__main__':
unittest.main()

View file

@ -5,90 +5,85 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
InlineQuery"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import User, Location, InlineQuery, Update
import telegram
from tests.base import BaseTest
class InlineQueryTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram InlineQuery.""" def inline_query(bot):
return InlineQuery(TestInlineQuery.id, TestInlineQuery.from_user, TestInlineQuery.query,
TestInlineQuery.offset, location=TestInlineQuery.location, bot=bot)
def setUp(self):
user = telegram.User(1, 'First name')
location = telegram.Location(8.8, 53.1)
self._id = 1234 class TestInlineQuery(object):
self.from_user = user id = 1234
self.query = 'query text' from_user = User(1, 'First name')
self.offset = 'offset' query = 'query text'
self.location = location offset = 'offset'
location = Location(8.8, 53.1)
self.json_dict = { def test_de_json(self, bot):
'id': self._id, json_dict = {
'id': self.id,
'from': self.from_user.to_dict(), 'from': self.from_user.to_dict(),
'query': self.query, 'query': self.query,
'offset': self.offset, 'offset': self.offset,
'location': self.location.to_dict() 'location': self.location.to_dict()
} }
inline_query_json = InlineQuery.de_json(json_dict, bot)
def test_inlinequery_de_json(self): assert inline_query_json.id == self.id
inlinequery = telegram.InlineQuery.de_json(self.json_dict, self._bot) assert inline_query_json.from_user == self.from_user
assert inline_query_json.location == self.location
assert inline_query_json.query == self.query
assert inline_query_json.offset == self.offset
self.assertEqual(inlinequery.id, self._id) def test_to_dict(self, inline_query):
self.assertDictEqual(inlinequery.from_user.to_dict(), self.from_user.to_dict()) inline_query_dict = inline_query.to_dict()
self.assertDictEqual(inlinequery.location.to_dict(), self.location.to_dict())
self.assertEqual(inlinequery.query, self.query)
self.assertEqual(inlinequery.offset, self.offset)
def test_inlinequery_to_json(self): assert isinstance(inline_query_dict, dict)
inlinequery = telegram.InlineQuery.de_json(self.json_dict, self._bot) assert inline_query_dict['id'] == inline_query.id
assert inline_query_dict['from'] == inline_query.from_user.to_dict()
assert inline_query_dict['location'] == inline_query.location.to_dict()
assert inline_query_dict['query'] == inline_query.query
assert inline_query_dict['offset'] == inline_query.offset
self.assertTrue(self.is_json(inlinequery.to_json())) def test_answer(self, monkeypatch, inline_query):
def test(*args, **kwargs):
return args[1] == inline_query.id
def test_inlinequery_to_dict(self): monkeypatch.setattr('telegram.Bot.answer_inline_query', test)
inlinequery = telegram.InlineQuery.de_json(self.json_dict, self._bot).to_dict() assert inline_query.answer()
self.assertTrue(self.is_dict(inlinequery))
self.assertDictEqual(inlinequery, self.json_dict)
def test_equality(self): def test_equality(self):
a = telegram.InlineQuery(self._id, telegram.User(1, ""), "", "") a = InlineQuery(self.id, User(1, ''), '', '')
b = telegram.InlineQuery(self._id, telegram.User(1, ""), "", "") b = InlineQuery(self.id, User(1, ''), '', '')
c = telegram.InlineQuery(self._id, telegram.User(0, ""), "", "") c = InlineQuery(self.id, User(0, ''), '', '')
d = telegram.InlineQuery(0, telegram.User(1, ""), "", "") d = InlineQuery(0, User(1, ''), '', '')
e = telegram.Update(self._id) e = Update(self.id)
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertEqual(a, c) assert a == c
self.assertEqual(hash(a), hash(c)) assert hash(a) == hash(c)
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
self.assertNotEqual(a, e) assert a != e
self.assertNotEqual(hash(a), hash(e)) assert hash(a) != hash(e)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,173 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
import pytest
from telegram import (Update, CallbackQuery, Bot, Message, User, Chat, InlineQuery,
ChosenInlineResult, ShippingQuery, PreCheckoutQuery, Location)
from telegram.ext import InlineQueryHandler
message = Message(1, User(1, ''), None, Chat(1, ''), text='Text')
params = [
{'message': message},
{'edited_message': message},
{'callback_query': CallbackQuery(1, User(1, ''), 'chat', message=message)},
{'channel_post': message},
{'edited_channel_post': message},
{'chosen_inline_result': ChosenInlineResult('id', User(1, ''), '')},
{'shipping_query': ShippingQuery('id', User(1, ''), '', None)},
{'pre_checkout_query': PreCheckoutQuery('id', User(1, ''), '', 0, '')},
{'callback_query': CallbackQuery(1, User(1, ''), 'chat')}
]
ids = ('message', 'edited_message', 'callback_query', 'channel_post',
'edited_channel_post', 'chosen_inline_result',
'shipping_query', 'pre_checkout_query', 'callback_query_without_message')
@pytest.fixture(scope='class', params=params, ids=ids)
def false_update(request):
return Update(update_id=2, **request.param)
@pytest.fixture(scope='function')
def inline_query(bot):
return Update(0, inline_query=InlineQuery('id', User(2, 'test user'),
'test query', offset='22',
location=Location(latitude=-23.691288,
longitude=-46.788279)))
class TestCallbackQueryHandler(object):
test_flag = False
@pytest.fixture(autouse=True)
def reset(self):
self.test_flag = False
def callback_basic(self, bot, update):
test_bot = isinstance(bot, Bot)
test_update = isinstance(update, Update)
self.test_flag = test_bot and test_update
def callback_data_1(self, bot, update, user_data=None, chat_data=None):
self.test_flag = (user_data is not None) or (chat_data is not None)
def callback_data_2(self, bot, update, user_data=None, chat_data=None):
self.test_flag = (user_data is not None) and (chat_data is not None)
def callback_queue_1(self, bot, update, job_queue=None, update_queue=None):
self.test_flag = (job_queue is not None) or (update_queue is not None)
def callback_queue_2(self, bot, update, job_queue=None, update_queue=None):
self.test_flag = (job_queue is not None) and (update_queue is not None)
def callback_group(self, bot, update, groups=None, groupdict=None):
if groups is not None:
self.test_flag = groups == ('t', ' query')
if groupdict is not None:
self.test_flag = groupdict == {'begin': 't', 'end': ' query'}
def test_basic(self, dp, inline_query):
handler = InlineQueryHandler(self.callback_basic)
dp.add_handler(handler)
assert handler.check_update(inline_query)
dp.process_update(inline_query)
assert self.test_flag
def test_with_pattern(self, inline_query):
handler = InlineQueryHandler(self.callback_basic, pattern='(?P<begin>.*)est(?P<end>.*)')
assert handler.check_update(inline_query)
inline_query.inline_query.query = 'nothing here'
assert not handler.check_update(inline_query)
def test_with_passing_group_dict(self, dp, inline_query):
handler = InlineQueryHandler(self.callback_group,
pattern='(?P<begin>.*)est(?P<end>.*)',
pass_groups=True)
dp.add_handler(handler)
dp.process_update(inline_query)
assert self.test_flag
dp.remove_handler(handler)
handler = InlineQueryHandler(self.callback_group,
pattern='(?P<begin>.*)est(?P<end>.*)',
pass_groupdict=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(inline_query)
assert self.test_flag
def test_pass_user_or_chat_data(self, dp, inline_query):
handler = InlineQueryHandler(self.callback_data_1, pass_user_data=True)
dp.add_handler(handler)
dp.process_update(inline_query)
assert self.test_flag
dp.remove_handler(handler)
handler = InlineQueryHandler(self.callback_data_1, pass_chat_data=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(inline_query)
assert self.test_flag
dp.remove_handler(handler)
handler = InlineQueryHandler(self.callback_data_2, pass_chat_data=True,
pass_user_data=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(inline_query)
assert self.test_flag
def test_pass_job_or_update_queue(self, dp, inline_query):
handler = InlineQueryHandler(self.callback_queue_1, pass_job_queue=True)
dp.add_handler(handler)
dp.process_update(inline_query)
assert self.test_flag
dp.remove_handler(handler)
handler = InlineQueryHandler(self.callback_queue_1, pass_update_queue=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(inline_query)
assert self.test_flag
dp.remove_handler(handler)
handler = InlineQueryHandler(self.callback_queue_2, pass_job_queue=True,
pass_update_queue=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(inline_query)
assert self.test_flag
def test_other_update_types(self, false_update):
handler = InlineQueryHandler(self.callback_basic)
assert not handler.check_update(false_update)

View file

@ -5,107 +5,103 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
InlineQueryResultArticle"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import (InlineKeyboardMarkup, InlineQueryResultAudio, InlineQueryResultArticle,
InlineKeyboardButton, InputTextMessageContent)
import telegram
from tests.base import BaseTest
class InlineQueryResultArticleTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram InlineQueryResultArticle.""" def inline_query_result_article():
return InlineQueryResultArticle(TestInlineQueryResultArticle.id,
TestInlineQueryResultArticle.title,
input_message_content=TestInlineQueryResultArticle.input_message_content,
reply_markup=TestInlineQueryResultArticle.reply_markup,
url=TestInlineQueryResultArticle.url,
hide_url=TestInlineQueryResultArticle.hide_url,
description=TestInlineQueryResultArticle.description,
thumb_url=TestInlineQueryResultArticle.thumb_url,
thumb_height=TestInlineQueryResultArticle.thumb_height,
thumb_width=TestInlineQueryResultArticle.thumb_width)
def setUp(self):
self._id = 'id'
self.type = 'article'
self.title = 'title'
self.input_message_content = telegram.InputTextMessageContent('input_message_content')
self.reply_markup = telegram.InlineKeyboardMarkup(
[[telegram.InlineKeyboardButton('reply_markup')]])
self.url = 'url'
self.hide_url = True
self.description = 'description'
self.thumb_url = 'thumb url'
self.thumb_height = 10
self.thumb_width = 15
self.json_dict = { class TestInlineQueryResultArticle(object):
'type': self.type, id = 'id'
'id': self._id, type = 'article'
'title': self.title, title = 'title'
'input_message_content': self.input_message_content.to_dict(), input_message_content = InputTextMessageContent('input_message_content')
'reply_markup': self.reply_markup.to_dict(), reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton('reply_markup')]])
'url': self.url, url = 'url'
'hide_url': self.hide_url, hide_url = True
'description': self.description, description = 'description'
'thumb_url': self.thumb_url, thumb_url = 'thumb url'
'thumb_height': self.thumb_height, thumb_height = 10
'thumb_width': self.thumb_width thumb_width = 15
}
def test_article_de_json(self): def test_expected_values(self, inline_query_result_article):
article = telegram.InlineQueryResultArticle.de_json(self.json_dict, self._bot) assert inline_query_result_article.type == self.type
assert inline_query_result_article.id == self.id
assert inline_query_result_article.title == self.title
assert inline_query_result_article.input_message_content.to_dict() == \
self.input_message_content.to_dict()
assert inline_query_result_article.reply_markup.to_dict() == self.reply_markup.to_dict()
assert inline_query_result_article.url == self.url
assert inline_query_result_article.hide_url == self.hide_url
assert inline_query_result_article.description == self.description
assert inline_query_result_article.thumb_url == self.thumb_url
assert inline_query_result_article.thumb_height == self.thumb_height
assert inline_query_result_article.thumb_width == self.thumb_width
self.assertEqual(article.type, self.type) def test_to_dict(self, inline_query_result_article):
self.assertEqual(article.id, self._id) inline_query_result_article_dict = inline_query_result_article.to_dict()
self.assertEqual(article.title, self.title)
self.assertDictEqual(article.input_message_content.to_dict(),
self.input_message_content.to_dict())
self.assertDictEqual(article.reply_markup.to_dict(), self.reply_markup.to_dict())
self.assertEqual(article.url, self.url)
self.assertEqual(article.hide_url, self.hide_url)
self.assertEqual(article.description, self.description)
self.assertEqual(article.thumb_url, self.thumb_url)
self.assertEqual(article.thumb_height, self.thumb_height)
self.assertEqual(article.thumb_width, self.thumb_width)
def test_article_to_json(self): assert isinstance(inline_query_result_article_dict, dict)
article = telegram.InlineQueryResultArticle.de_json(self.json_dict, self._bot) assert inline_query_result_article_dict['type'] == inline_query_result_article.type
assert inline_query_result_article_dict['id'] == inline_query_result_article.id
self.assertTrue(self.is_json(article.to_json())) assert inline_query_result_article_dict['title'] == inline_query_result_article.title
assert inline_query_result_article_dict['input_message_content'] == \
def test_article_to_dict(self): inline_query_result_article.input_message_content.to_dict()
article = telegram.InlineQueryResultArticle.de_json(self.json_dict, self._bot).to_dict() assert inline_query_result_article_dict['reply_markup'] == \
inline_query_result_article.reply_markup.to_dict()
self.assertTrue(self.is_dict(article)) assert inline_query_result_article_dict['url'] == inline_query_result_article.url
self.assertDictEqual(self.json_dict, article) assert inline_query_result_article_dict['hide_url'] == inline_query_result_article.hide_url
assert inline_query_result_article_dict['description'] == \
inline_query_result_article.description
assert inline_query_result_article_dict['thumb_url'] == \
inline_query_result_article.thumb_url
assert inline_query_result_article_dict['thumb_height'] == \
inline_query_result_article.thumb_height
assert inline_query_result_article_dict['thumb_width'] == \
inline_query_result_article.thumb_width
def test_equality(self): def test_equality(self):
a = telegram.InlineQueryResultArticle(self._id, self.title, self.input_message_content) a = InlineQueryResultArticle(self.id, self.title, self.input_message_content)
b = telegram.InlineQueryResultArticle(self._id, self.title, self.input_message_content) b = InlineQueryResultArticle(self.id, self.title, self.input_message_content)
c = telegram.InlineQueryResultArticle(self._id, "", self.input_message_content) c = InlineQueryResultArticle(self.id, '', self.input_message_content)
d = telegram.InlineQueryResultArticle("", self.title, self.input_message_content) d = InlineQueryResultArticle('', self.title, self.input_message_content)
e = telegram.InlineQueryResultAudio(self._id, "", "") e = InlineQueryResultAudio(self.id, '', '')
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertEqual(a, c) assert a == c
self.assertEqual(hash(a), hash(c)) assert hash(a) == hash(c)
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
self.assertNotEqual(a, e) assert a != e
self.assertNotEqual(hash(a), hash(e)) assert hash(a) != hash(e)
if __name__ == '__main__':
unittest.main()

View file

@ -5,101 +5,92 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
InlineQueryResultAudio"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import (InlineKeyboardMarkup, InlineKeyboardButton, InlineQueryResultAudio,
InputTextMessageContent, InlineQueryResultVoice)
import telegram
from tests.base import BaseTest
class InlineQueryResultAudioTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram InlineQueryResultAudio.""" def inline_query_result_audio():
return InlineQueryResultAudio(TestInlineQueryResultAudio.id,
TestInlineQueryResultAudio.audio_url,
TestInlineQueryResultAudio.title,
performer=TestInlineQueryResultAudio.performer,
audio_duration=TestInlineQueryResultAudio.audio_duration,
caption=TestInlineQueryResultAudio.caption,
input_message_content=TestInlineQueryResultAudio.input_message_content,
reply_markup=TestInlineQueryResultAudio.reply_markup)
def setUp(self):
self._id = 'id'
self.type = 'audio'
self.audio_url = 'audio url'
self.title = 'title'
self.performer = 'performer'
self.audio_duration = 'audio_duration'
self.caption = 'caption'
self.input_message_content = telegram.InputTextMessageContent('input_message_content')
self.reply_markup = telegram.InlineKeyboardMarkup(
[[telegram.InlineKeyboardButton('reply_markup')]])
self.json_dict = { class TestInlineQueryResultAudio(object):
'type': self.type, id = 'id'
'id': self._id, type = 'audio'
'audio_url': self.audio_url, audio_url = 'audio url'
'title': self.title, title = 'title'
'performer': self.performer, performer = 'performer'
'audio_duration': self.audio_duration, audio_duration = 'audio_duration'
'caption': self.caption, caption = 'caption'
'input_message_content': self.input_message_content.to_dict(), input_message_content = InputTextMessageContent('input_message_content')
'reply_markup': self.reply_markup.to_dict(), reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton('reply_markup')]])
}
def test_audio_de_json(self): def test_expected_values(self, inline_query_result_audio):
audio = telegram.InlineQueryResultAudio.de_json(self.json_dict, self._bot) assert inline_query_result_audio.type == self.type
assert inline_query_result_audio.id == self.id
assert inline_query_result_audio.audio_url == self.audio_url
assert inline_query_result_audio.title == self.title
assert inline_query_result_audio.performer == self.performer
assert inline_query_result_audio.audio_duration == self.audio_duration
assert inline_query_result_audio.caption == self.caption
assert inline_query_result_audio.input_message_content.to_dict() == \
self.input_message_content.to_dict()
assert inline_query_result_audio.reply_markup.to_dict() == self.reply_markup.to_dict()
self.assertEqual(audio.type, self.type) def test_to_dict(self, inline_query_result_audio):
self.assertEqual(audio.id, self._id) inline_query_result_audio_dict = inline_query_result_audio.to_dict()
self.assertEqual(audio.audio_url, self.audio_url)
self.assertEqual(audio.title, self.title)
self.assertEqual(audio.performer, self.performer)
self.assertEqual(audio.audio_duration, self.audio_duration)
self.assertEqual(audio.caption, self.caption)
self.assertDictEqual(audio.input_message_content.to_dict(),
self.input_message_content.to_dict())
self.assertDictEqual(audio.reply_markup.to_dict(), self.reply_markup.to_dict())
def test_audio_to_json(self): assert isinstance(inline_query_result_audio_dict, dict)
audio = telegram.InlineQueryResultAudio.de_json(self.json_dict, self._bot) assert inline_query_result_audio_dict['type'] == inline_query_result_audio.type
assert inline_query_result_audio_dict['id'] == inline_query_result_audio.id
self.assertTrue(self.is_json(audio.to_json())) assert inline_query_result_audio_dict['audio_url'] == inline_query_result_audio.audio_url
assert inline_query_result_audio_dict['title'] == inline_query_result_audio.title
def test_audio_to_dict(self): assert inline_query_result_audio_dict['performer'] == inline_query_result_audio.performer
audio = telegram.InlineQueryResultAudio.de_json(self.json_dict, self._bot).to_dict() assert inline_query_result_audio_dict['audio_duration'] == \
inline_query_result_audio.audio_duration
self.assertTrue(self.is_dict(audio)) assert inline_query_result_audio_dict['caption'] == inline_query_result_audio.caption
self.assertDictEqual(self.json_dict, audio) assert inline_query_result_audio_dict['input_message_content'] == \
inline_query_result_audio.input_message_content.to_dict()
assert inline_query_result_audio_dict['reply_markup'] == \
inline_query_result_audio.reply_markup.to_dict()
def test_equality(self): def test_equality(self):
a = telegram.InlineQueryResultAudio(self._id, self.audio_url, self.title) a = InlineQueryResultAudio(self.id, self.audio_url, self.title)
b = telegram.InlineQueryResultAudio(self._id, self.title, self.title) b = InlineQueryResultAudio(self.id, self.title, self.title)
c = telegram.InlineQueryResultAudio(self._id, "", self.title) c = InlineQueryResultAudio(self.id, '', self.title)
d = telegram.InlineQueryResultAudio("", self.audio_url, self.title) d = InlineQueryResultAudio('', self.audio_url, self.title)
e = telegram.InlineQueryResultArticle(self._id, "", "") e = InlineQueryResultVoice(self.id, '', '')
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertEqual(a, c) assert a == c
self.assertEqual(hash(a), hash(c)) assert hash(a) == hash(c)
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
self.assertNotEqual(a, e) assert a != e
self.assertNotEqual(hash(a), hash(e)) assert hash(a) != hash(e)
if __name__ == '__main__':
unittest.main()

View file

@ -5,93 +5,83 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
InlineQueryResultCachedAudio"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import (InputTextMessageContent, InlineQueryResultCachedAudio, InlineKeyboardMarkup,
InlineKeyboardButton, InlineQueryResultCachedVoice)
import telegram
from tests.base import BaseTest
class InlineQueryResultCachedAudioTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram def inline_query_result_cached_audio():
InlineQueryResultCachedAudio.""" return InlineQueryResultCachedAudio(TestInlineQueryResultCachedAudio.id,
TestInlineQueryResultCachedAudio.audio_file_id,
caption=TestInlineQueryResultCachedAudio.caption,
input_message_content=TestInlineQueryResultCachedAudio.input_message_content,
reply_markup=TestInlineQueryResultCachedAudio.reply_markup)
def setUp(self):
self._id = 'id'
self.type = 'audio'
self.audio_file_id = 'audio file id'
self.caption = 'caption'
self.input_message_content = telegram.InputTextMessageContent('input_message_content')
self.reply_markup = telegram.InlineKeyboardMarkup(
[[telegram.InlineKeyboardButton('reply_markup')]])
self.json_dict = { class TestInlineQueryResultCachedAudio(object):
'type': self.type, id = 'id'
'id': self._id, type = 'audio'
'audio_file_id': self.audio_file_id, audio_file_id = 'audio file id'
'caption': self.caption, caption = 'caption'
'input_message_content': self.input_message_content.to_dict(), input_message_content = InputTextMessageContent('input_message_content')
'reply_markup': self.reply_markup.to_dict(), reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton('reply_markup')]])
}
def test_audio_de_json(self): def test_expected_values(self, inline_query_result_cached_audio):
audio = telegram.InlineQueryResultCachedAudio.de_json(self.json_dict, self._bot) assert inline_query_result_cached_audio.type == self.type
assert inline_query_result_cached_audio.id == self.id
assert inline_query_result_cached_audio.audio_file_id == self.audio_file_id
assert inline_query_result_cached_audio.caption == self.caption
assert inline_query_result_cached_audio.input_message_content.to_dict() == \
self.input_message_content.to_dict()
assert inline_query_result_cached_audio.reply_markup.to_dict() == \
self.reply_markup.to_dict()
self.assertEqual(audio.type, self.type) def test_to_dict(self, inline_query_result_cached_audio):
self.assertEqual(audio.id, self._id) inline_query_result_cached_audio_dict = inline_query_result_cached_audio.to_dict()
self.assertEqual(audio.audio_file_id, self.audio_file_id)
self.assertEqual(audio.caption, self.caption)
self.assertDictEqual(audio.input_message_content.to_dict(),
self.input_message_content.to_dict())
self.assertDictEqual(audio.reply_markup.to_dict(), self.reply_markup.to_dict())
def test_audio_to_json(self): assert isinstance(inline_query_result_cached_audio_dict, dict)
audio = telegram.InlineQueryResultCachedAudio.de_json(self.json_dict, self._bot) assert inline_query_result_cached_audio_dict['type'] == \
inline_query_result_cached_audio.type
self.assertTrue(self.is_json(audio.to_json())) assert inline_query_result_cached_audio_dict['id'] == inline_query_result_cached_audio.id
assert inline_query_result_cached_audio_dict['audio_file_id'] == \
def test_audio_to_dict(self): inline_query_result_cached_audio.audio_file_id
audio = telegram.InlineQueryResultCachedAudio.de_json(self.json_dict, self._bot).to_dict() assert inline_query_result_cached_audio_dict['caption'] == \
inline_query_result_cached_audio.caption
self.assertTrue(self.is_dict(audio)) assert inline_query_result_cached_audio_dict['input_message_content'] == \
self.assertDictEqual(self.json_dict, audio) inline_query_result_cached_audio.input_message_content.to_dict()
assert inline_query_result_cached_audio_dict['reply_markup'] == \
inline_query_result_cached_audio.reply_markup.to_dict()
def test_equality(self): def test_equality(self):
a = telegram.InlineQueryResultCachedAudio(self._id, self.audio_file_id) a = InlineQueryResultCachedAudio(self.id, self.audio_file_id)
b = telegram.InlineQueryResultCachedAudio(self._id, self.audio_file_id) b = InlineQueryResultCachedAudio(self.id, self.audio_file_id)
c = telegram.InlineQueryResultCachedAudio(self._id, "") c = InlineQueryResultCachedAudio(self.id, '')
d = telegram.InlineQueryResultCachedAudio("", self.audio_file_id) d = InlineQueryResultCachedAudio('', self.audio_file_id)
e = telegram.InlineQueryResultCachedVoice(self._id, "", "") e = InlineQueryResultCachedVoice(self.id, '', '')
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertEqual(a, c) assert a == c
self.assertEqual(hash(a), hash(c)) assert hash(a) == hash(c)
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
self.assertNotEqual(a, e) assert a != e
self.assertNotEqual(hash(a), hash(e)) assert hash(a) != hash(e)
if __name__ == '__main__':
unittest.main()

View file

@ -5,99 +5,94 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
InlineQueryResultCachedDocument"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import (InlineQueryResultCachedDocument, InlineKeyboardButton, InlineKeyboardMarkup,
InputTextMessageContent, InlineQueryResultCachedVoice)
import telegram
from tests.base import BaseTest
class InlineQueryResultCachedDocumentTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram def inline_query_result_cached_document():
InlineQueryResultCachedDocument.""" return InlineQueryResultCachedDocument(TestInlineQueryResultCachedDocument.id,
TestInlineQueryResultCachedDocument.title,
TestInlineQueryResultCachedDocument.document_file_id,
caption=TestInlineQueryResultCachedDocument.caption,
description=TestInlineQueryResultCachedDocument.description,
input_message_content=TestInlineQueryResultCachedDocument.input_message_content,
reply_markup=TestInlineQueryResultCachedDocument.reply_markup)
def setUp(self):
self._id = 'id'
self.type = 'document'
self.document_file_id = 'document file id'
self.title = 'title'
self.caption = 'caption'
self.description = 'description'
self.input_message_content = telegram.InputTextMessageContent('input_message_content')
self.reply_markup = telegram.InlineKeyboardMarkup(
[[telegram.InlineKeyboardButton('reply_markup')]])
self.json_dict = {
'id': self._id,
'type': self.type,
'document_file_id': self.document_file_id,
'title': self.title,
'caption': self.caption,
'description': self.description,
'input_message_content': self.input_message_content.to_dict(),
'reply_markup': self.reply_markup.to_dict(),
}
def test_document_de_json(self): class TestInlineQueryResultCachedDocument(object):
document = telegram.InlineQueryResultCachedDocument.de_json(self.json_dict, self._bot) id = 'id'
type = 'document'
document_file_id = 'document file id'
title = 'title'
caption = 'caption'
description = 'description'
input_message_content = InputTextMessageContent('input_message_content')
reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton('reply_markup')]])
self.assertEqual(document.id, self._id) def test_expected_values(self, inline_query_result_cached_document):
self.assertEqual(document.type, self.type) assert inline_query_result_cached_document.id == self.id
self.assertEqual(document.document_file_id, self.document_file_id) assert inline_query_result_cached_document.type == self.type
self.assertEqual(document.title, self.title) assert inline_query_result_cached_document.document_file_id == self.document_file_id
self.assertEqual(document.caption, self.caption) assert inline_query_result_cached_document.title == self.title
self.assertEqual(document.description, self.description) assert inline_query_result_cached_document.caption == self.caption
self.assertDictEqual(document.input_message_content.to_dict(), assert inline_query_result_cached_document.description == self.description
self.input_message_content.to_dict()) assert inline_query_result_cached_document.input_message_content.to_dict() == \
self.assertDictEqual(document.reply_markup.to_dict(), self.reply_markup.to_dict()) self.input_message_content.to_dict()
assert inline_query_result_cached_document.reply_markup.to_dict() == \
self.reply_markup.to_dict()
def test_document_to_json(self): def test_to_dict(self, inline_query_result_cached_document):
document = telegram.InlineQueryResultCachedDocument.de_json(self.json_dict, self._bot) inline_query_result_cached_document_dict = inline_query_result_cached_document.to_dict()
self.assertTrue(self.is_json(document.to_json())) assert isinstance(inline_query_result_cached_document_dict, dict)
assert inline_query_result_cached_document_dict['id'] == \
def test_document_to_dict(self): inline_query_result_cached_document.id
document = telegram.InlineQueryResultCachedDocument.de_json(self.json_dict, assert inline_query_result_cached_document_dict['type'] == \
self._bot).to_dict() inline_query_result_cached_document.type
assert inline_query_result_cached_document_dict['document_file_id'] == \
self.assertTrue(self.is_dict(document)) inline_query_result_cached_document.document_file_id
self.assertDictEqual(self.json_dict, document) assert inline_query_result_cached_document_dict['title'] == \
inline_query_result_cached_document.title
assert inline_query_result_cached_document_dict['caption'] == \
inline_query_result_cached_document.caption
assert inline_query_result_cached_document_dict['description'] == \
inline_query_result_cached_document.description
assert inline_query_result_cached_document_dict['input_message_content'] == \
inline_query_result_cached_document.input_message_content.to_dict()
assert inline_query_result_cached_document_dict['reply_markup'] == \
inline_query_result_cached_document.reply_markup.to_dict()
def test_equality(self): def test_equality(self):
a = telegram.InlineQueryResultCachedDocument(self._id, self.title, self.document_file_id) a = InlineQueryResultCachedDocument(self.id, self.title, self.document_file_id)
b = telegram.InlineQueryResultCachedDocument(self._id, self.title, self.document_file_id) b = InlineQueryResultCachedDocument(self.id, self.title, self.document_file_id)
c = telegram.InlineQueryResultCachedDocument(self._id, self.title, "") c = InlineQueryResultCachedDocument(self.id, self.title, '')
d = telegram.InlineQueryResultCachedDocument("", self.title, self.document_file_id) d = InlineQueryResultCachedDocument('', self.title, self.document_file_id)
e = telegram.InlineQueryResultCachedVoice(self._id, "", "") e = InlineQueryResultCachedVoice(self.id, '', '')
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertEqual(a, c) assert a == c
self.assertEqual(hash(a), hash(c)) assert hash(a) == hash(c)
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
self.assertNotEqual(a, e) assert a != e
self.assertNotEqual(hash(a), hash(e)) assert hash(a) != hash(e)
if __name__ == '__main__':
unittest.main()

View file

@ -5,95 +5,85 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
InlineQueryResultCachedGif"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import (InlineKeyboardButton, InputTextMessageContent, InlineQueryResultCachedVoice,
InlineKeyboardMarkup, InlineQueryResultCachedGif)
import telegram
from tests.base import BaseTest
class InlineQueryResultCachedGifTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram InlineQueryResultCachedGif.""" def inline_query_result_cached_gif():
return InlineQueryResultCachedGif(TestInlineQueryResultCachedGif.id,
TestInlineQueryResultCachedGif.gif_file_id,
title=TestInlineQueryResultCachedGif.title,
caption=TestInlineQueryResultCachedGif.caption,
input_message_content=TestInlineQueryResultCachedGif.input_message_content,
reply_markup=TestInlineQueryResultCachedGif.reply_markup)
def setUp(self):
self._id = 'id'
self.type = 'gif'
self.gif_file_id = 'gif file id'
self.title = 'title'
self.caption = 'caption'
self.input_message_content = telegram.InputTextMessageContent('input_message_content')
self.reply_markup = telegram.InlineKeyboardMarkup(
[[telegram.InlineKeyboardButton('reply_markup')]])
self.json_dict = { class TestInlineQueryResultCachedGif(object):
'type': self.type, id = 'id'
'id': self._id, type = 'gif'
'gif_file_id': self.gif_file_id, gif_file_id = 'gif file id'
'title': self.title, title = 'title'
'caption': self.caption, caption = 'caption'
'input_message_content': self.input_message_content.to_dict(), input_message_content = InputTextMessageContent('input_message_content')
'reply_markup': self.reply_markup.to_dict(), reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton('reply_markup')]])
}
def test_gif_de_json(self): def test_expected_values(self, inline_query_result_cached_gif):
gif = telegram.InlineQueryResultCachedGif.de_json(self.json_dict, self._bot) assert inline_query_result_cached_gif.type == self.type
assert inline_query_result_cached_gif.id == self.id
assert inline_query_result_cached_gif.gif_file_id == self.gif_file_id
assert inline_query_result_cached_gif.title == self.title
assert inline_query_result_cached_gif.caption == self.caption
assert inline_query_result_cached_gif.input_message_content.to_dict() == \
self.input_message_content.to_dict()
assert inline_query_result_cached_gif.reply_markup.to_dict() == self.reply_markup.to_dict()
self.assertEqual(gif.type, self.type) def test_to_dict(self, inline_query_result_cached_gif):
self.assertEqual(gif.id, self._id) inline_query_result_cached_gif_dict = inline_query_result_cached_gif.to_dict()
self.assertEqual(gif.gif_file_id, self.gif_file_id)
self.assertEqual(gif.title, self.title)
self.assertEqual(gif.caption, self.caption)
self.assertDictEqual(gif.input_message_content.to_dict(),
self.input_message_content.to_dict())
self.assertDictEqual(gif.reply_markup.to_dict(), self.reply_markup.to_dict())
def test_gif_to_json(self): assert isinstance(inline_query_result_cached_gif_dict, dict)
gif = telegram.InlineQueryResultCachedGif.de_json(self.json_dict, self._bot) assert inline_query_result_cached_gif_dict['type'] == inline_query_result_cached_gif.type
assert inline_query_result_cached_gif_dict['id'] == inline_query_result_cached_gif.id
self.assertTrue(self.is_json(gif.to_json())) assert inline_query_result_cached_gif_dict['gif_file_id'] == \
inline_query_result_cached_gif.gif_file_id
def test_gif_to_dict(self): assert inline_query_result_cached_gif_dict['title'] == inline_query_result_cached_gif.title
gif = telegram.InlineQueryResultCachedGif.de_json(self.json_dict, self._bot).to_dict() assert inline_query_result_cached_gif_dict['caption'] == \
inline_query_result_cached_gif.caption
self.assertTrue(self.is_dict(gif)) assert inline_query_result_cached_gif_dict['input_message_content'] == \
self.assertDictEqual(self.json_dict, gif) inline_query_result_cached_gif.input_message_content.to_dict()
assert inline_query_result_cached_gif_dict['reply_markup'] == \
inline_query_result_cached_gif.reply_markup.to_dict()
def test_equality(self): def test_equality(self):
a = telegram.InlineQueryResultCachedGif(self._id, self.gif_file_id) a = InlineQueryResultCachedGif(self.id, self.gif_file_id)
b = telegram.InlineQueryResultCachedGif(self._id, self.gif_file_id) b = InlineQueryResultCachedGif(self.id, self.gif_file_id)
c = telegram.InlineQueryResultCachedGif(self._id, "") c = InlineQueryResultCachedGif(self.id, '')
d = telegram.InlineQueryResultCachedGif("", self.gif_file_id) d = InlineQueryResultCachedGif('', self.gif_file_id)
e = telegram.InlineQueryResultCachedVoice(self._id, "", "") e = InlineQueryResultCachedVoice(self.id, '', '')
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertEqual(a, c) assert a == c
self.assertEqual(hash(a), hash(c)) assert hash(a) == hash(c)
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
self.assertNotEqual(a, e) assert a != e
self.assertNotEqual(hash(a), hash(e)) assert hash(a) != hash(e)
if __name__ == '__main__':
unittest.main()

View file

@ -5,97 +5,89 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
InlineQueryResultCachedMpeg4Gif"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import (InlineQueryResultCachedMpeg4Gif, InlineKeyboardButton,
InputTextMessageContent, InlineKeyboardMarkup, InlineQueryResultCachedVoice)
import telegram
from tests.base import BaseTest
class InlineQueryResultCachedMpeg4GifTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram def inline_query_result_cached_mpeg4_gif():
InlineQueryResultCachedMpeg4Gif.""" return InlineQueryResultCachedMpeg4Gif(TestInlineQueryResultCachedMpeg4Gif.id,
TestInlineQueryResultCachedMpeg4Gif.mpeg4_file_id,
title=TestInlineQueryResultCachedMpeg4Gif.title,
caption=TestInlineQueryResultCachedMpeg4Gif.caption,
input_message_content=TestInlineQueryResultCachedMpeg4Gif.input_message_content,
reply_markup=TestInlineQueryResultCachedMpeg4Gif.reply_markup)
def setUp(self):
self._id = 'id'
self.type = 'mpeg4_gif'
self.mpeg4_file_id = 'mpeg4 file id'
self.title = 'title'
self.caption = 'caption'
self.input_message_content = telegram.InputTextMessageContent('input_message_content')
self.reply_markup = telegram.InlineKeyboardMarkup(
[[telegram.InlineKeyboardButton('reply_markup')]])
self.json_dict = { class TestInlineQueryResultCachedMpeg4Gif(object):
'type': self.type, id = 'id'
'id': self._id, type = 'mpeg4_gif'
'mpeg4_file_id': self.mpeg4_file_id, mpeg4_file_id = 'mpeg4 file id'
'title': self.title, title = 'title'
'caption': self.caption, caption = 'caption'
'input_message_content': self.input_message_content.to_dict(), input_message_content = InputTextMessageContent('input_message_content')
'reply_markup': self.reply_markup.to_dict(), reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton('reply_markup')]])
}
def test_mpeg4_de_json(self): def test_expected_values(self, inline_query_result_cached_mpeg4_gif):
mpeg4 = telegram.InlineQueryResultCachedMpeg4Gif.de_json(self.json_dict, self._bot) assert inline_query_result_cached_mpeg4_gif.type == self.type
assert inline_query_result_cached_mpeg4_gif.id == self.id
assert inline_query_result_cached_mpeg4_gif.mpeg4_file_id == self.mpeg4_file_id
assert inline_query_result_cached_mpeg4_gif.title == self.title
assert inline_query_result_cached_mpeg4_gif.caption == self.caption
assert inline_query_result_cached_mpeg4_gif.input_message_content.to_dict() == \
self.input_message_content.to_dict()
assert inline_query_result_cached_mpeg4_gif.reply_markup.to_dict() == \
self.reply_markup.to_dict()
self.assertEqual(mpeg4.type, self.type) def test_to_dict(self, inline_query_result_cached_mpeg4_gif):
self.assertEqual(mpeg4.id, self._id) inline_query_result_cached_mpeg4_gif_dict = inline_query_result_cached_mpeg4_gif.to_dict()
self.assertEqual(mpeg4.mpeg4_file_id, self.mpeg4_file_id)
self.assertEqual(mpeg4.title, self.title)
self.assertEqual(mpeg4.caption, self.caption)
self.assertDictEqual(mpeg4.input_message_content.to_dict(),
self.input_message_content.to_dict())
self.assertDictEqual(mpeg4.reply_markup.to_dict(), self.reply_markup.to_dict())
def test_mpeg4_to_json(self): assert isinstance(inline_query_result_cached_mpeg4_gif_dict, dict)
mpeg4 = telegram.InlineQueryResultCachedMpeg4Gif.de_json(self.json_dict, self._bot) assert inline_query_result_cached_mpeg4_gif_dict['type'] == \
inline_query_result_cached_mpeg4_gif.type
self.assertTrue(self.is_json(mpeg4.to_json())) assert inline_query_result_cached_mpeg4_gif_dict['id'] == \
inline_query_result_cached_mpeg4_gif.id
def test_mpeg4_to_dict(self): assert inline_query_result_cached_mpeg4_gif_dict['mpeg4_file_id'] == \
mpeg4 = telegram.InlineQueryResultCachedMpeg4Gif.de_json(self.json_dict, inline_query_result_cached_mpeg4_gif.mpeg4_file_id
self._bot).to_dict() assert inline_query_result_cached_mpeg4_gif_dict['title'] == \
inline_query_result_cached_mpeg4_gif.title
self.assertTrue(self.is_dict(mpeg4)) assert inline_query_result_cached_mpeg4_gif_dict['caption'] == \
self.assertDictEqual(self.json_dict, mpeg4) inline_query_result_cached_mpeg4_gif.caption
assert inline_query_result_cached_mpeg4_gif_dict['input_message_content'] == \
inline_query_result_cached_mpeg4_gif.input_message_content.to_dict()
assert inline_query_result_cached_mpeg4_gif_dict['reply_markup'] == \
inline_query_result_cached_mpeg4_gif.reply_markup.to_dict()
def test_equality(self): def test_equality(self):
a = telegram.InlineQueryResultCachedMpeg4Gif(self._id, self.mpeg4_file_id) a = InlineQueryResultCachedMpeg4Gif(self.id, self.mpeg4_file_id)
b = telegram.InlineQueryResultCachedMpeg4Gif(self._id, self.mpeg4_file_id) b = InlineQueryResultCachedMpeg4Gif(self.id, self.mpeg4_file_id)
c = telegram.InlineQueryResultCachedMpeg4Gif(self._id, "") c = InlineQueryResultCachedMpeg4Gif(self.id, '')
d = telegram.InlineQueryResultCachedMpeg4Gif("", self.mpeg4_file_id) d = InlineQueryResultCachedMpeg4Gif('', self.mpeg4_file_id)
e = telegram.InlineQueryResultCachedVoice(self._id, "", "") e = InlineQueryResultCachedVoice(self.id, '', '')
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertEqual(a, c) assert a == c
self.assertEqual(hash(a), hash(c)) assert hash(a) == hash(c)
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
self.assertNotEqual(a, e) assert a != e
self.assertNotEqual(hash(a), hash(e)) assert hash(a) != hash(e)
if __name__ == '__main__':
unittest.main()

View file

@ -5,99 +5,93 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
InlineQueryResultCachedPhoto"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import (InputTextMessageContent, InlineQueryResultCachedPhoto, InlineKeyboardButton,
InlineQueryResultCachedVoice, InlineKeyboardMarkup)
import telegram
from tests.base import BaseTest
class InlineQueryResultCachedPhotoTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram def inline_query_result_cached_photo():
InlineQueryResultCachedPhoto.""" return InlineQueryResultCachedPhoto(TestInlineQueryResultCachedPhoto.id,
TestInlineQueryResultCachedPhoto.photo_file_id,
title=TestInlineQueryResultCachedPhoto.title,
description=TestInlineQueryResultCachedPhoto.description,
caption=TestInlineQueryResultCachedPhoto.caption,
input_message_content=TestInlineQueryResultCachedPhoto.input_message_content,
reply_markup=TestInlineQueryResultCachedPhoto.reply_markup)
def setUp(self):
self._id = 'id'
self.type = 'photo'
self.photo_file_id = 'photo file id'
self.title = 'title'
self.description = 'description'
self.caption = 'caption'
self.input_message_content = telegram.InputTextMessageContent('input_message_content')
self.reply_markup = telegram.InlineKeyboardMarkup(
[[telegram.InlineKeyboardButton('reply_markup')]])
self.json_dict = { class TestInlineQueryResultCachedPhoto(object):
'type': self.type, id = 'id'
'id': self._id, type = 'photo'
'photo_file_id': self.photo_file_id, photo_file_id = 'photo file id'
'title': self.title, title = 'title'
'description': self.description, description = 'description'
'caption': self.caption, caption = 'caption'
'input_message_content': self.input_message_content.to_dict(), input_message_content = InputTextMessageContent('input_message_content')
'reply_markup': self.reply_markup.to_dict(), reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton('reply_markup')]])
}
def test_photo_de_json(self): def test_expected_values(self, inline_query_result_cached_photo):
photo = telegram.InlineQueryResultCachedPhoto.de_json(self.json_dict, self._bot) assert inline_query_result_cached_photo.type == self.type
assert inline_query_result_cached_photo.id == self.id
assert inline_query_result_cached_photo.photo_file_id == self.photo_file_id
assert inline_query_result_cached_photo.title == self.title
assert inline_query_result_cached_photo.description == self.description
assert inline_query_result_cached_photo.caption == self.caption
assert inline_query_result_cached_photo.input_message_content.to_dict() == \
self.input_message_content.to_dict()
assert inline_query_result_cached_photo.reply_markup.to_dict() == \
self.reply_markup.to_dict()
self.assertEqual(photo.type, self.type) def test_to_dict(self, inline_query_result_cached_photo):
self.assertEqual(photo.id, self._id) inline_query_result_cached_photo_dict = inline_query_result_cached_photo.to_dict()
self.assertEqual(photo.photo_file_id, self.photo_file_id)
self.assertEqual(photo.title, self.title)
self.assertEqual(photo.description, self.description)
self.assertEqual(photo.caption, self.caption)
self.assertDictEqual(photo.input_message_content.to_dict(),
self.input_message_content.to_dict())
self.assertDictEqual(photo.reply_markup.to_dict(), self.reply_markup.to_dict())
def test_photo_to_json(self): assert isinstance(inline_query_result_cached_photo_dict, dict)
photo = telegram.InlineQueryResultCachedPhoto.de_json(self.json_dict, self._bot) assert inline_query_result_cached_photo_dict['type'] == \
inline_query_result_cached_photo.type
self.assertTrue(self.is_json(photo.to_json())) assert inline_query_result_cached_photo_dict['id'] == inline_query_result_cached_photo.id
assert inline_query_result_cached_photo_dict['photo_file_id'] == \
def test_photo_to_dict(self): inline_query_result_cached_photo.photo_file_id
photo = telegram.InlineQueryResultCachedPhoto.de_json(self.json_dict, self._bot).to_dict() assert inline_query_result_cached_photo_dict['title'] == \
inline_query_result_cached_photo.title
self.assertTrue(self.is_dict(photo)) assert inline_query_result_cached_photo_dict['description'] == \
self.assertDictEqual(self.json_dict, photo) inline_query_result_cached_photo.description
assert inline_query_result_cached_photo_dict['caption'] == \
inline_query_result_cached_photo.caption
assert inline_query_result_cached_photo_dict['input_message_content'] == \
inline_query_result_cached_photo.input_message_content.to_dict()
assert inline_query_result_cached_photo_dict['reply_markup'] == \
inline_query_result_cached_photo.reply_markup.to_dict()
def test_equality(self): def test_equality(self):
a = telegram.InlineQueryResultCachedPhoto(self._id, self.photo_file_id) a = InlineQueryResultCachedPhoto(self.id, self.photo_file_id)
b = telegram.InlineQueryResultCachedPhoto(self._id, self.photo_file_id) b = InlineQueryResultCachedPhoto(self.id, self.photo_file_id)
c = telegram.InlineQueryResultCachedPhoto(self._id, "") c = InlineQueryResultCachedPhoto(self.id, '')
d = telegram.InlineQueryResultCachedPhoto("", self.photo_file_id) d = InlineQueryResultCachedPhoto('', self.photo_file_id)
e = telegram.InlineQueryResultCachedVoice(self._id, "", "") e = InlineQueryResultCachedVoice(self.id, '', '')
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertEqual(a, c) assert a == c
self.assertEqual(hash(a), hash(c)) assert hash(a) == hash(c)
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
self.assertNotEqual(a, e) assert a != e
self.assertNotEqual(hash(a), hash(e)) assert hash(a) != hash(e)
if __name__ == '__main__':
unittest.main()

View file

@ -5,91 +5,80 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
InlineQueryResultCachedSticker"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import (InputTextMessageContent, InlineKeyboardButton,
InlineQueryResultCachedSticker, InlineQueryResultCachedVoice,
import telegram InlineKeyboardMarkup)
from tests.base import BaseTest
class InlineQueryResultCachedStickerTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram def inline_query_result_cached_sticker():
InlineQueryResultCachedSticker.""" return InlineQueryResultCachedSticker(TestInlineQueryResultCachedSticker.id,
TestInlineQueryResultCachedSticker.sticker_file_id,
input_message_content=TestInlineQueryResultCachedSticker.input_message_content,
reply_markup=TestInlineQueryResultCachedSticker.reply_markup)
def setUp(self):
self._id = 'id'
self.type = 'sticker'
self.sticker_file_id = 'sticker file id'
self.input_message_content = telegram.InputTextMessageContent('input_message_content')
self.reply_markup = telegram.InlineKeyboardMarkup(
[[telegram.InlineKeyboardButton('reply_markup')]])
self.json_dict = { class TestInlineQueryResultCachedSticker(object):
'type': self.type, id = 'id'
'id': self._id, type = 'sticker'
'sticker_file_id': self.sticker_file_id, sticker_file_id = 'sticker file id'
'input_message_content': self.input_message_content.to_dict(), input_message_content = InputTextMessageContent('input_message_content')
'reply_markup': self.reply_markup.to_dict(), reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton('reply_markup')]])
}
def test_sticker_de_json(self): def test_expected_values(self, inline_query_result_cached_sticker):
sticker = telegram.InlineQueryResultCachedSticker.de_json(self.json_dict, self._bot) assert inline_query_result_cached_sticker.type == self.type
assert inline_query_result_cached_sticker.id == self.id
assert inline_query_result_cached_sticker.sticker_file_id == self.sticker_file_id
assert inline_query_result_cached_sticker.input_message_content.to_dict() == \
self.input_message_content.to_dict()
assert inline_query_result_cached_sticker.reply_markup.to_dict() == \
self.reply_markup.to_dict()
self.assertEqual(sticker.type, self.type) def test_to_dict(self, inline_query_result_cached_sticker):
self.assertEqual(sticker.id, self._id) inline_query_result_cached_sticker_dict = inline_query_result_cached_sticker.to_dict()
self.assertEqual(sticker.sticker_file_id, self.sticker_file_id)
self.assertDictEqual(sticker.input_message_content.to_dict(),
self.input_message_content.to_dict())
self.assertDictEqual(sticker.reply_markup.to_dict(), self.reply_markup.to_dict())
def test_sticker_to_json(self): assert isinstance(inline_query_result_cached_sticker_dict, dict)
sticker = telegram.InlineQueryResultCachedSticker.de_json(self.json_dict, self._bot) assert inline_query_result_cached_sticker_dict['type'] == \
inline_query_result_cached_sticker.type
self.assertTrue(self.is_json(sticker.to_json())) assert inline_query_result_cached_sticker_dict['id'] == \
inline_query_result_cached_sticker.id
def test_sticker_to_dict(self): assert inline_query_result_cached_sticker_dict['sticker_file_id'] == \
sticker = telegram.InlineQueryResultCachedSticker.de_json(self.json_dict, inline_query_result_cached_sticker.sticker_file_id
self._bot).to_dict() assert inline_query_result_cached_sticker_dict['input_message_content'] == \
inline_query_result_cached_sticker.input_message_content.to_dict()
self.assertTrue(self.is_dict(sticker)) assert inline_query_result_cached_sticker_dict['reply_markup'] == \
self.assertDictEqual(self.json_dict, sticker) inline_query_result_cached_sticker.reply_markup.to_dict()
def test_equality(self): def test_equality(self):
a = telegram.InlineQueryResultCachedSticker(self._id, self.sticker_file_id) a = InlineQueryResultCachedSticker(self.id, self.sticker_file_id)
b = telegram.InlineQueryResultCachedSticker(self._id, self.sticker_file_id) b = InlineQueryResultCachedSticker(self.id, self.sticker_file_id)
c = telegram.InlineQueryResultCachedSticker(self._id, "") c = InlineQueryResultCachedSticker(self.id, '')
d = telegram.InlineQueryResultCachedSticker("", self.sticker_file_id) d = InlineQueryResultCachedSticker('', self.sticker_file_id)
e = telegram.InlineQueryResultCachedVoice(self._id, "", "") e = InlineQueryResultCachedVoice(self.id, '', '')
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertEqual(a, c) assert a == c
self.assertEqual(hash(a), hash(c)) assert hash(a) == hash(c)
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
self.assertNotEqual(a, e) assert a != e
self.assertNotEqual(hash(a), hash(e)) assert hash(a) != hash(e)
if __name__ == '__main__':
unittest.main()

View file

@ -5,99 +5,93 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
InlineQueryResultCachedVideo"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import (InlineKeyboardMarkup, InlineKeyboardButton, InputTextMessageContent,
InlineQueryResultCachedVideo, InlineQueryResultCachedVoice)
import telegram
from tests.base import BaseTest
class InlineQueryResultCachedVideoTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram def inline_query_result_cached_video():
InlineQueryResultCachedVideo.""" return InlineQueryResultCachedVideo(TestInlineQueryResultCachedVideo.id,
TestInlineQueryResultCachedVideo.video_file_id,
TestInlineQueryResultCachedVideo.title,
caption=TestInlineQueryResultCachedVideo.caption,
description=TestInlineQueryResultCachedVideo.description,
input_message_content=TestInlineQueryResultCachedVideo.input_message_content,
reply_markup=TestInlineQueryResultCachedVideo.reply_markup)
def setUp(self):
self._id = 'id'
self.type = 'video'
self.video_file_id = 'video file id'
self.title = 'title'
self.caption = 'caption'
self.description = 'description'
self.input_message_content = telegram.InputTextMessageContent('input_message_content')
self.reply_markup = telegram.InlineKeyboardMarkup(
[[telegram.InlineKeyboardButton('reply_markup')]])
self.json_dict = { class TestInlineQueryResultCachedVideo(object):
'type': self.type, id = 'id'
'id': self._id, type = 'video'
'video_file_id': self.video_file_id, video_file_id = 'video file id'
'title': self.title, title = 'title'
'caption': self.caption, caption = 'caption'
'description': self.description, description = 'description'
'input_message_content': self.input_message_content.to_dict(), input_message_content = InputTextMessageContent('input_message_content')
'reply_markup': self.reply_markup.to_dict(), reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton('reply_markup')]])
}
def test_video_de_json(self): def test_expected_values(self, inline_query_result_cached_video):
video = telegram.InlineQueryResultCachedVideo.de_json(self.json_dict, self._bot) assert inline_query_result_cached_video.type == self.type
assert inline_query_result_cached_video.id == self.id
assert inline_query_result_cached_video.video_file_id == self.video_file_id
assert inline_query_result_cached_video.title == self.title
assert inline_query_result_cached_video.description == self.description
assert inline_query_result_cached_video.caption == self.caption
assert inline_query_result_cached_video.input_message_content.to_dict() == \
self.input_message_content.to_dict()
assert inline_query_result_cached_video.reply_markup.to_dict() == \
self.reply_markup.to_dict()
self.assertEqual(video.type, self.type) def test_to_dict(self, inline_query_result_cached_video):
self.assertEqual(video.id, self._id) inline_query_result_cached_video_dict = inline_query_result_cached_video.to_dict()
self.assertEqual(video.video_file_id, self.video_file_id)
self.assertEqual(video.title, self.title)
self.assertEqual(video.description, self.description)
self.assertEqual(video.caption, self.caption)
self.assertDictEqual(video.input_message_content.to_dict(),
self.input_message_content.to_dict())
self.assertDictEqual(video.reply_markup.to_dict(), self.reply_markup.to_dict())
def test_video_to_json(self): assert isinstance(inline_query_result_cached_video_dict, dict)
video = telegram.InlineQueryResultCachedVideo.de_json(self.json_dict, self._bot) assert inline_query_result_cached_video_dict['type'] == \
inline_query_result_cached_video.type
self.assertTrue(self.is_json(video.to_json())) assert inline_query_result_cached_video_dict['id'] == inline_query_result_cached_video.id
assert inline_query_result_cached_video_dict['video_file_id'] == \
def test_video_to_dict(self): inline_query_result_cached_video.video_file_id
video = telegram.InlineQueryResultCachedVideo.de_json(self.json_dict, self._bot).to_dict() assert inline_query_result_cached_video_dict['title'] == \
inline_query_result_cached_video.title
self.assertTrue(self.is_dict(video)) assert inline_query_result_cached_video_dict['description'] == \
self.assertDictEqual(self.json_dict, video) inline_query_result_cached_video.description
assert inline_query_result_cached_video_dict['caption'] == \
inline_query_result_cached_video.caption
assert inline_query_result_cached_video_dict['input_message_content'] == \
inline_query_result_cached_video.input_message_content.to_dict()
assert inline_query_result_cached_video_dict['reply_markup'] == \
inline_query_result_cached_video.reply_markup.to_dict()
def test_equality(self): def test_equality(self):
a = telegram.InlineQueryResultCachedVideo(self._id, self.video_file_id, self.title) a = InlineQueryResultCachedVideo(self.id, self.video_file_id, self.title)
b = telegram.InlineQueryResultCachedVideo(self._id, self.video_file_id, self.title) b = InlineQueryResultCachedVideo(self.id, self.video_file_id, self.title)
c = telegram.InlineQueryResultCachedVideo(self._id, "", self.title) c = InlineQueryResultCachedVideo(self.id, '', self.title)
d = telegram.InlineQueryResultCachedVideo("", self.video_file_id, self.title) d = InlineQueryResultCachedVideo('', self.video_file_id, self.title)
e = telegram.InlineQueryResultCachedVoice(self._id, "", "") e = InlineQueryResultCachedVoice(self.id, '', '')
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertEqual(a, c) assert a == c
self.assertEqual(hash(a), hash(c)) assert hash(a) == hash(c)
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
self.assertNotEqual(a, e) assert a != e
self.assertNotEqual(hash(a), hash(e)) assert hash(a) != hash(e)
if __name__ == '__main__':
unittest.main()

View file

@ -5,96 +5,88 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
InlineQueryResultCachedVoice"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import (InlineQueryResultCachedVoice, InlineKeyboardButton, InlineKeyboardMarkup,
InlineQueryResultCachedAudio, InputTextMessageContent)
import telegram
from tests.base import BaseTest
class InlineQueryResultCachedVoiceTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram def inline_query_result_cached_voice():
InlineQueryResultCachedVoice.""" return InlineQueryResultCachedVoice(TestInlineQueryResultCachedVoice.id,
TestInlineQueryResultCachedVoice.voice_file_id,
TestInlineQueryResultCachedVoice.title,
caption=TestInlineQueryResultCachedVoice.caption,
input_message_content=TestInlineQueryResultCachedVoice.input_message_content,
reply_markup=TestInlineQueryResultCachedVoice.reply_markup)
def setUp(self):
self._id = 'id'
self.type = 'voice'
self.voice_file_id = 'voice file id'
self.title = 'title'
self.caption = 'caption'
self.input_message_content = telegram.InputTextMessageContent('input_message_content')
self.reply_markup = telegram.InlineKeyboardMarkup(
[[telegram.InlineKeyboardButton('reply_markup')]])
self.json_dict = { class TestInlineQueryResultCachedVoice(object):
'type': self.type, id = 'id'
'id': self._id, type = 'voice'
'voice_file_id': self.voice_file_id, voice_file_id = 'voice file id'
'title': self.title, title = 'title'
'caption': self.caption, caption = 'caption'
'input_message_content': self.input_message_content.to_dict(), input_message_content = InputTextMessageContent('input_message_content')
'reply_markup': self.reply_markup.to_dict(), reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton('reply_markup')]])
}
def test_voice_de_json(self): def test_expected_values(self, inline_query_result_cached_voice):
voice = telegram.InlineQueryResultCachedVoice.de_json(self.json_dict, self._bot) assert inline_query_result_cached_voice.type == self.type
assert inline_query_result_cached_voice.id == self.id
assert inline_query_result_cached_voice.voice_file_id == self.voice_file_id
assert inline_query_result_cached_voice.title == self.title
assert inline_query_result_cached_voice.caption == self.caption
assert inline_query_result_cached_voice.input_message_content.to_dict() == \
self.input_message_content.to_dict()
assert inline_query_result_cached_voice.reply_markup.to_dict() == \
self.reply_markup.to_dict()
self.assertEqual(voice.type, self.type) def test_to_dict(self, inline_query_result_cached_voice):
self.assertEqual(voice.id, self._id) inline_query_result_cached_voice_dict = inline_query_result_cached_voice.to_dict()
self.assertEqual(voice.voice_file_id, self.voice_file_id)
self.assertEqual(voice.title, self.title)
self.assertEqual(voice.caption, self.caption)
self.assertDictEqual(voice.input_message_content.to_dict(),
self.input_message_content.to_dict())
self.assertDictEqual(voice.reply_markup.to_dict(), self.reply_markup.to_dict())
def test_voice_to_json(self): assert isinstance(inline_query_result_cached_voice_dict, dict)
voice = telegram.InlineQueryResultCachedVoice.de_json(self.json_dict, self._bot) assert inline_query_result_cached_voice_dict['type'] == \
inline_query_result_cached_voice.type
self.assertTrue(self.is_json(voice.to_json())) assert inline_query_result_cached_voice_dict['id'] == inline_query_result_cached_voice.id
assert inline_query_result_cached_voice_dict['voice_file_id'] == \
def test_voice_to_dict(self): inline_query_result_cached_voice.voice_file_id
voice = telegram.InlineQueryResultCachedVoice.de_json(self.json_dict, self._bot).to_dict() assert inline_query_result_cached_voice_dict['title'] == \
inline_query_result_cached_voice.title
self.assertTrue(self.is_dict(voice)) assert inline_query_result_cached_voice_dict['caption'] == \
self.assertDictEqual(self.json_dict, voice) inline_query_result_cached_voice.caption
assert inline_query_result_cached_voice_dict['input_message_content'] == \
inline_query_result_cached_voice.input_message_content.to_dict()
assert inline_query_result_cached_voice_dict['reply_markup'] == \
inline_query_result_cached_voice.reply_markup.to_dict()
def test_equality(self): def test_equality(self):
a = telegram.InlineQueryResultCachedVoice(self._id, self.voice_file_id, self.title) a = InlineQueryResultCachedVoice(self.id, self.voice_file_id, self.title)
b = telegram.InlineQueryResultCachedVoice(self._id, self.voice_file_id, self.title) b = InlineQueryResultCachedVoice(self.id, self.voice_file_id, self.title)
c = telegram.InlineQueryResultCachedVoice(self._id, "", self.title) c = InlineQueryResultCachedVoice(self.id, '', self.title)
d = telegram.InlineQueryResultCachedVoice("", self.voice_file_id, self.title) d = InlineQueryResultCachedVoice('', self.voice_file_id, self.title)
e = telegram.InlineQueryResultCachedAudio(self._id, "", "") e = InlineQueryResultCachedAudio(self.id, '', '')
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertEqual(a, c) assert a == c
self.assertEqual(hash(a), hash(c)) assert hash(a) == hash(c)
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
self.assertNotEqual(a, e) assert a != e
self.assertNotEqual(hash(a), hash(e)) assert hash(a) != hash(e)
if __name__ == '__main__':
unittest.main()

View file

@ -5,103 +5,101 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
InlineQueryResultContact"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import (InlineQueryResultVoice, InputTextMessageContent, InlineKeyboardButton,
InlineKeyboardMarkup, InlineQueryResultContact)
import telegram
from tests.base import BaseTest
class InlineQueryResultContactTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram InlineQueryResultContact.""" def inline_query_result_contact():
return InlineQueryResultContact(TestInlineQueryResultContact.id,
TestInlineQueryResultContact.phone_number,
TestInlineQueryResultContact.first_name,
last_name=TestInlineQueryResultContact.last_name,
thumb_url=TestInlineQueryResultContact.thumb_url,
thumb_width=TestInlineQueryResultContact.thumb_width,
thumb_height=TestInlineQueryResultContact.thumb_height,
input_message_content=TestInlineQueryResultContact.input_message_content,
reply_markup=TestInlineQueryResultContact.reply_markup)
def setUp(self):
self._id = 'id'
self.type = 'contact'
self.phone_number = 'phone_number'
self.first_name = 'first_name'
self.last_name = 'last_name'
self.thumb_url = 'thumb url'
self.thumb_width = 10
self.thumb_height = 15
self.input_message_content = telegram.InputTextMessageContent('input_message_content')
self.reply_markup = telegram.InlineKeyboardMarkup(
[[telegram.InlineKeyboardButton('reply_markup')]])
self.json_dict = {
'id': self._id,
'type': self.type,
'phone_number': self.phone_number,
'first_name': self.first_name,
'last_name': self.last_name,
'thumb_url': self.thumb_url,
'thumb_width': self.thumb_width,
'thumb_height': self.thumb_height,
'input_message_content': self.input_message_content.to_dict(),
'reply_markup': self.reply_markup.to_dict(),
}
def test_contact_de_json(self): class TestInlineQueryResultContact(object):
contact = telegram.InlineQueryResultContact.de_json(self.json_dict, self._bot) id = 'id'
type = 'contact'
phone_number = 'phone_number'
first_name = 'first_name'
last_name = 'last_name'
thumb_url = 'thumb url'
thumb_width = 10
thumb_height = 15
input_message_content = InputTextMessageContent('input_message_content')
reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton('reply_markup')]])
self.assertEqual(contact.id, self._id) def test_expected_values(self, inline_query_result_contact):
self.assertEqual(contact.type, self.type) assert inline_query_result_contact.id == self.id
self.assertEqual(contact.phone_number, self.phone_number) assert inline_query_result_contact.type == self.type
self.assertEqual(contact.first_name, self.first_name) assert inline_query_result_contact.phone_number == self.phone_number
self.assertEqual(contact.last_name, self.last_name) assert inline_query_result_contact.first_name == self.first_name
self.assertEqual(contact.thumb_url, self.thumb_url) assert inline_query_result_contact.last_name == self.last_name
self.assertEqual(contact.thumb_width, self.thumb_width) assert inline_query_result_contact.thumb_url == self.thumb_url
self.assertEqual(contact.thumb_height, self.thumb_height) assert inline_query_result_contact.thumb_width == self.thumb_width
self.assertDictEqual(contact.input_message_content.to_dict(), assert inline_query_result_contact.thumb_height == self.thumb_height
self.input_message_content.to_dict()) assert inline_query_result_contact.input_message_content.to_dict() == \
self.assertDictEqual(contact.reply_markup.to_dict(), self.reply_markup.to_dict()) self.input_message_content.to_dict()
assert inline_query_result_contact.reply_markup.to_dict() == self.reply_markup.to_dict()
def test_contact_to_json(self): def test_to_dict(self, inline_query_result_contact):
contact = telegram.InlineQueryResultContact.de_json(self.json_dict, self._bot) inline_query_result_contact_dict = inline_query_result_contact.to_dict()
self.assertTrue(self.is_json(contact.to_json())) assert isinstance(inline_query_result_contact_dict, dict)
assert inline_query_result_contact_dict['id'] == inline_query_result_contact.id
def test_contact_to_dict(self): assert inline_query_result_contact_dict['type'] == inline_query_result_contact.type
contact = telegram.InlineQueryResultContact.de_json(self.json_dict, self._bot).to_dict() assert inline_query_result_contact_dict['phone_number'] == \
inline_query_result_contact.phone_number
self.assertTrue(self.is_dict(contact)) assert inline_query_result_contact_dict['first_name'] == \
self.assertDictEqual(self.json_dict, contact) inline_query_result_contact.first_name
assert inline_query_result_contact_dict['last_name'] == \
inline_query_result_contact.last_name
assert inline_query_result_contact_dict['thumb_url'] == \
inline_query_result_contact.thumb_url
assert inline_query_result_contact_dict['thumb_width'] == \
inline_query_result_contact.thumb_width
assert inline_query_result_contact_dict['thumb_height'] == \
inline_query_result_contact.thumb_height
assert inline_query_result_contact_dict['input_message_content'] == \
inline_query_result_contact.input_message_content.to_dict()
assert inline_query_result_contact_dict['reply_markup'] == \
inline_query_result_contact.reply_markup.to_dict()
def test_equality(self): def test_equality(self):
a = telegram.InlineQueryResultContact(self._id, self.phone_number, self.first_name) a = InlineQueryResultContact(self.id, self.phone_number, self.first_name)
b = telegram.InlineQueryResultContact(self._id, self.phone_number, self.first_name) b = InlineQueryResultContact(self.id, self.phone_number, self.first_name)
c = telegram.InlineQueryResultContact(self._id, "", self.first_name) c = InlineQueryResultContact(self.id, '', self.first_name)
d = telegram.InlineQueryResultContact("", self.phone_number, self.first_name) d = InlineQueryResultContact('', self.phone_number, self.first_name)
e = telegram.InlineQueryResultArticle(self._id, "", "") e = InlineQueryResultVoice(self.id, '', '')
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertEqual(a, c) assert a == c
self.assertEqual(hash(a), hash(c)) assert hash(a) == hash(c)
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
self.assertNotEqual(a, e) assert a != e
self.assertNotEqual(hash(a), hash(e)) assert hash(a) != hash(e)
if __name__ == '__main__':
unittest.main()

View file

@ -5,111 +5,111 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
InlineQueryResultDocument"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import (InlineKeyboardButton, InputTextMessageContent, InlineQueryResultDocument,
InlineKeyboardMarkup, InlineQueryResultVoice)
import telegram
from tests.base import BaseTest
class InlineQueryResultDocumentTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram InlineQueryResultDocument.""" def inline_query_result_document():
return InlineQueryResultDocument(TestInlineQueryResultDocument.id,
TestInlineQueryResultDocument.document_url,
TestInlineQueryResultDocument.title,
TestInlineQueryResultDocument.mime_type,
caption=TestInlineQueryResultDocument.caption,
description=TestInlineQueryResultDocument.description,
thumb_url=TestInlineQueryResultDocument.thumb_url,
thumb_width=TestInlineQueryResultDocument.thumb_width,
thumb_height=TestInlineQueryResultDocument.thumb_height,
input_message_content=TestInlineQueryResultDocument.input_message_content,
reply_markup=TestInlineQueryResultDocument.reply_markup)
def setUp(self):
self._id = 'id'
self.type = 'document'
self.document_url = 'document url'
self.title = 'title'
self.caption = 'caption'
self.mime_type = 'mime type'
self.description = 'description'
self.thumb_url = 'thumb url'
self.thumb_width = 10
self.thumb_height = 15
self.input_message_content = telegram.InputTextMessageContent('input_message_content')
self.reply_markup = telegram.InlineKeyboardMarkup(
[[telegram.InlineKeyboardButton('reply_markup')]])
self.json_dict = {
'id': self._id,
'type': self.type,
'document_url': self.document_url,
'title': self.title,
'caption': self.caption,
'mime_type': self.mime_type,
'description': self.description,
'thumb_url': self.thumb_url,
'thumb_width': self.thumb_width,
'thumb_height': self.thumb_height,
'input_message_content': self.input_message_content.to_dict(),
'reply_markup': self.reply_markup.to_dict(),
}
def test_document_de_json(self): class TestInlineQueryResultDocument(object):
document = telegram.InlineQueryResultDocument.de_json(self.json_dict, self._bot) id = 'id'
type = 'document'
document_url = 'document url'
title = 'title'
caption = 'caption'
mime_type = 'mime type'
description = 'description'
thumb_url = 'thumb url'
thumb_width = 10
thumb_height = 15
input_message_content = InputTextMessageContent('input_message_content')
reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton('reply_markup')]])
self.assertEqual(document.id, self._id) def test_expected_values(self, inline_query_result_document):
self.assertEqual(document.type, self.type) assert inline_query_result_document.id == self.id
self.assertEqual(document.document_url, self.document_url) assert inline_query_result_document.type == self.type
self.assertEqual(document.title, self.title) assert inline_query_result_document.document_url == self.document_url
self.assertEqual(document.caption, self.caption) assert inline_query_result_document.title == self.title
self.assertEqual(document.mime_type, self.mime_type) assert inline_query_result_document.caption == self.caption
self.assertEqual(document.description, self.description) assert inline_query_result_document.mime_type == self.mime_type
self.assertEqual(document.thumb_url, self.thumb_url) assert inline_query_result_document.description == self.description
self.assertEqual(document.thumb_width, self.thumb_width) assert inline_query_result_document.thumb_url == self.thumb_url
self.assertEqual(document.thumb_height, self.thumb_height) assert inline_query_result_document.thumb_width == self.thumb_width
self.assertDictEqual(document.input_message_content.to_dict(), assert inline_query_result_document.thumb_height == self.thumb_height
self.input_message_content.to_dict()) assert inline_query_result_document.input_message_content.to_dict() == \
self.assertDictEqual(document.reply_markup.to_dict(), self.reply_markup.to_dict()) self.input_message_content.to_dict()
assert inline_query_result_document.reply_markup.to_dict() == self.reply_markup.to_dict()
def test_document_to_json(self): def test_to_dict(self, inline_query_result_document):
document = telegram.InlineQueryResultDocument.de_json(self.json_dict, self._bot) inline_query_result_document_dict = inline_query_result_document.to_dict()
self.assertTrue(self.is_json(document.to_json())) assert isinstance(inline_query_result_document_dict, dict)
assert inline_query_result_document_dict['id'] == inline_query_result_document.id
def test_document_to_dict(self): assert inline_query_result_document_dict['type'] == inline_query_result_document.type
document = telegram.InlineQueryResultDocument.de_json(self.json_dict, self._bot).to_dict() assert inline_query_result_document_dict['document_url'] == \
inline_query_result_document.document_url
self.assertTrue(self.is_dict(document)) assert inline_query_result_document_dict['title'] == inline_query_result_document.title
self.assertDictEqual(self.json_dict, document) assert inline_query_result_document_dict['caption'] == inline_query_result_document.caption
assert inline_query_result_document_dict['mime_type'] == \
inline_query_result_document.mime_type
assert inline_query_result_document_dict['description'] == \
inline_query_result_document.description
assert inline_query_result_document_dict['thumb_url'] == \
inline_query_result_document.thumb_url
assert inline_query_result_document_dict['thumb_width'] == \
inline_query_result_document.thumb_width
assert inline_query_result_document_dict['thumb_height'] == \
inline_query_result_document.thumb_height
assert inline_query_result_document_dict['input_message_content'] == \
inline_query_result_document.input_message_content.to_dict()
assert inline_query_result_document_dict['reply_markup'] == \
inline_query_result_document.reply_markup.to_dict()
def test_equality(self): def test_equality(self):
a = telegram.InlineQueryResultDocument(self._id, self.document_url, self.title, a = InlineQueryResultDocument(self.id, self.document_url, self.title,
self.mime_type) self.mime_type)
b = telegram.InlineQueryResultDocument(self._id, self.document_url, self.title, b = InlineQueryResultDocument(self.id, self.document_url, self.title,
self.mime_type) self.mime_type)
c = telegram.InlineQueryResultDocument(self._id, "", self.title, self.mime_type) c = InlineQueryResultDocument(self.id, '', self.title, self.mime_type)
d = telegram.InlineQueryResultDocument("", self.document_url, self.title, self.mime_type) d = InlineQueryResultDocument('', self.document_url, self.title, self.mime_type)
e = telegram.InlineQueryResultArticle(self._id, "", "") e = InlineQueryResultVoice(self.id, '', '')
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertEqual(a, c) assert a == c
self.assertEqual(hash(a), hash(c)) assert hash(a) == hash(c)
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
self.assertNotEqual(a, e) assert a != e
self.assertNotEqual(hash(a), hash(e)) assert hash(a) != hash(e)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,75 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
import pytest
from telegram import (InlineKeyboardButton, InlineQueryResultGame,
InlineQueryResultVoice, InlineKeyboardMarkup)
@pytest.fixture(scope='class')
def inline_query_result_game():
return InlineQueryResultGame(TestInlineQueryResultGame.id,
TestInlineQueryResultGame.game_short_name,
reply_markup=TestInlineQueryResultGame.reply_markup)
class TestInlineQueryResultGame(object):
id = 'id'
type = 'game'
game_short_name = 'game short name'
reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton('reply_markup')]])
def test_expected_values(self, inline_query_result_game):
assert inline_query_result_game.type == self.type
assert inline_query_result_game.id == self.id
assert inline_query_result_game.game_short_name == self.game_short_name
assert inline_query_result_game.reply_markup.to_dict() == \
self.reply_markup.to_dict()
def test_to_dict(self, inline_query_result_game):
inline_query_result_game_dict = inline_query_result_game.to_dict()
assert isinstance(inline_query_result_game_dict, dict)
assert inline_query_result_game_dict['type'] == inline_query_result_game.type
assert inline_query_result_game_dict['id'] == inline_query_result_game.id
assert inline_query_result_game_dict['game_short_name'] == \
inline_query_result_game.game_short_name
assert inline_query_result_game_dict['reply_markup'] == \
inline_query_result_game.reply_markup.to_dict()
def test_equality(self):
a = InlineQueryResultGame(self.id, self.game_short_name)
b = InlineQueryResultGame(self.id, self.game_short_name)
c = InlineQueryResultGame(self.id, '')
d = InlineQueryResultGame('', self.game_short_name)
e = InlineQueryResultVoice(self.id, '', '')
assert a == b
assert hash(a) == hash(b)
assert a is not b
assert a == c
assert hash(a) == hash(c)
assert a != d
assert hash(a) != hash(d)
assert a != e
assert hash(a) != hash(e)

View file

@ -5,107 +5,99 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
InlineQueryResultGif"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import (InlineKeyboardButton, InputTextMessageContent, InlineQueryResultGif,
InlineQueryResultVoice, InlineKeyboardMarkup)
import telegram
from tests.base import BaseTest
class InlineQueryResultGifTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram InlineQueryResultGif.""" def inline_query_result_gif():
return InlineQueryResultGif(TestInlineQueryResultGif.id,
TestInlineQueryResultGif.gif_url,
TestInlineQueryResultGif.thumb_url,
gif_width=TestInlineQueryResultGif.gif_width,
gif_height=TestInlineQueryResultGif.gif_height,
gif_duration=TestInlineQueryResultGif.gif_duration,
title=TestInlineQueryResultGif.title,
caption=TestInlineQueryResultGif.caption,
input_message_content=TestInlineQueryResultGif.input_message_content,
reply_markup=TestInlineQueryResultGif.reply_markup)
def setUp(self):
self._id = 'id'
self.type = 'gif'
self.gif_url = 'gif url'
self.gif_width = 10
self.gif_height = 15
self.gif_duration = 1
self.thumb_url = 'thumb url'
self.title = 'title'
self.caption = 'caption'
self.input_message_content = telegram.InputTextMessageContent('input_message_content')
self.reply_markup = telegram.InlineKeyboardMarkup(
[[telegram.InlineKeyboardButton('reply_markup')]])
self.json_dict = { class TestInlineQueryResultGif(object):
'type': self.type, id = 'id'
'id': self._id, type = 'gif'
'gif_url': self.gif_url, gif_url = 'gif url'
'gif_width': self.gif_width, gif_width = 10
'gif_height': self.gif_height, gif_height = 15
'gif_duration': self.gif_duration, gif_duration = 1
'thumb_url': self.thumb_url, thumb_url = 'thumb url'
'title': self.title, title = 'title'
'caption': self.caption, caption = 'caption'
'input_message_content': self.input_message_content.to_dict(), input_message_content = InputTextMessageContent('input_message_content')
'reply_markup': self.reply_markup.to_dict(), reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton('reply_markup')]])
}
def test_gif_de_json(self): def test_expected_values(self, inline_query_result_gif):
gif = telegram.InlineQueryResultGif.de_json(self.json_dict, self._bot) assert inline_query_result_gif.type == self.type
assert inline_query_result_gif.id == self.id
assert inline_query_result_gif.gif_url == self.gif_url
assert inline_query_result_gif.gif_width == self.gif_width
assert inline_query_result_gif.gif_height == self.gif_height
assert inline_query_result_gif.gif_duration == self.gif_duration
assert inline_query_result_gif.thumb_url == self.thumb_url
assert inline_query_result_gif.title == self.title
assert inline_query_result_gif.caption == self.caption
assert inline_query_result_gif.input_message_content.to_dict() == \
self.input_message_content.to_dict()
assert inline_query_result_gif.reply_markup.to_dict() == self.reply_markup.to_dict()
self.assertEqual(gif.type, self.type) def test_to_dict(self, inline_query_result_gif):
self.assertEqual(gif.id, self._id) inline_query_result_gif_dict = inline_query_result_gif.to_dict()
self.assertEqual(gif.gif_url, self.gif_url)
self.assertEqual(gif.gif_width, self.gif_width)
self.assertEqual(gif.gif_height, self.gif_height)
self.assertEqual(gif.gif_duration, self.gif_duration)
self.assertEqual(gif.thumb_url, self.thumb_url)
self.assertEqual(gif.title, self.title)
self.assertEqual(gif.caption, self.caption)
self.assertDictEqual(gif.input_message_content.to_dict(),
self.input_message_content.to_dict())
self.assertDictEqual(gif.reply_markup.to_dict(), self.reply_markup.to_dict())
def test_gif_to_json(self): assert isinstance(inline_query_result_gif_dict, dict)
gif = telegram.InlineQueryResultGif.de_json(self.json_dict, self._bot) assert inline_query_result_gif_dict['type'] == inline_query_result_gif.type
assert inline_query_result_gif_dict['id'] == inline_query_result_gif.id
self.assertTrue(self.is_json(gif.to_json())) assert inline_query_result_gif_dict['gif_url'] == inline_query_result_gif.gif_url
assert inline_query_result_gif_dict['gif_width'] == inline_query_result_gif.gif_width
def test_gif_to_dict(self): assert inline_query_result_gif_dict['gif_height'] == inline_query_result_gif.gif_height
gif = telegram.InlineQueryResultGif.de_json(self.json_dict, self._bot).to_dict() assert inline_query_result_gif_dict['gif_duration'] == inline_query_result_gif.gif_duration
assert inline_query_result_gif_dict['thumb_url'] == inline_query_result_gif.thumb_url
self.assertTrue(self.is_dict(gif)) assert inline_query_result_gif_dict['title'] == inline_query_result_gif.title
self.assertDictEqual(self.json_dict, gif) assert inline_query_result_gif_dict['caption'] == inline_query_result_gif.caption
assert inline_query_result_gif_dict['input_message_content'] == \
inline_query_result_gif.input_message_content.to_dict()
assert inline_query_result_gif_dict['reply_markup'] == \
inline_query_result_gif.reply_markup.to_dict()
def test_equality(self): def test_equality(self):
a = telegram.InlineQueryResultGif(self._id, self.gif_url, self.thumb_url) a = InlineQueryResultGif(self.id, self.gif_url, self.thumb_url)
b = telegram.InlineQueryResultGif(self._id, self.gif_url, self.thumb_url) b = InlineQueryResultGif(self.id, self.gif_url, self.thumb_url)
c = telegram.InlineQueryResultGif(self._id, "", self.thumb_url) c = InlineQueryResultGif(self.id, '', self.thumb_url)
d = telegram.InlineQueryResultGif("", self.gif_url, self.thumb_url) d = InlineQueryResultGif('', self.gif_url, self.thumb_url)
e = telegram.InlineQueryResultArticle(self._id, "", "") e = InlineQueryResultVoice(self.id, '', '')
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertEqual(a, c) assert a == c
self.assertEqual(hash(a), hash(c)) assert hash(a) == hash(c)
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
self.assertNotEqual(a, e) assert a != e
self.assertNotEqual(hash(a), hash(e)) assert hash(a) != hash(e)
if __name__ == '__main__':
unittest.main()

View file

@ -5,103 +5,100 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
InlineQueryResultLocation"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import (InputTextMessageContent, InlineQueryResultLocation, InlineKeyboardButton,
InlineQueryResultVoice, InlineKeyboardMarkup)
import telegram
from tests.base import BaseTest
class InlineQueryResultLocationTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram InlineQueryResultLocation.""" def inline_query_result_location():
return InlineQueryResultLocation(TestInlineQueryResultLocation.id,
TestInlineQueryResultLocation.latitude,
TestInlineQueryResultLocation.longitude,
TestInlineQueryResultLocation.title,
thumb_url=TestInlineQueryResultLocation.thumb_url,
thumb_width=TestInlineQueryResultLocation.thumb_width,
thumb_height=TestInlineQueryResultLocation.thumb_height,
input_message_content=TestInlineQueryResultLocation.input_message_content,
reply_markup=TestInlineQueryResultLocation.reply_markup)
def setUp(self):
self._id = 'id'
self.type = 'location'
self.latitude = 0.0
self.longitude = 0.0
self.title = 'title'
self.thumb_url = 'thumb url'
self.thumb_width = 10
self.thumb_height = 15
self.input_message_content = telegram.InputTextMessageContent('input_message_content')
self.reply_markup = telegram.InlineKeyboardMarkup(
[[telegram.InlineKeyboardButton('reply_markup')]])
self.json_dict = {
'id': self._id,
'type': self.type,
'latitude': self.latitude,
'longitude': self.longitude,
'title': self.title,
'thumb_url': self.thumb_url,
'thumb_width': self.thumb_width,
'thumb_height': self.thumb_height,
'input_message_content': self.input_message_content.to_dict(),
'reply_markup': self.reply_markup.to_dict(),
}
def test_location_de_json(self): class TestInlineQueryResultLocation(object):
location = telegram.InlineQueryResultLocation.de_json(self.json_dict, self._bot) id = 'id'
type = 'location'
latitude = 0.0
longitude = 1.0
title = 'title'
thumb_url = 'thumb url'
thumb_width = 10
thumb_height = 15
input_message_content = InputTextMessageContent('input_message_content')
reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton('reply_markup')]])
self.assertEqual(location.id, self._id) def test_expected_values(self, inline_query_result_location):
self.assertEqual(location.type, self.type) assert inline_query_result_location.id == self.id
self.assertEqual(location.latitude, self.latitude) assert inline_query_result_location.type == self.type
self.assertEqual(location.longitude, self.longitude) assert inline_query_result_location.latitude == self.latitude
self.assertEqual(location.title, self.title) assert inline_query_result_location.longitude == self.longitude
self.assertEqual(location.thumb_url, self.thumb_url) assert inline_query_result_location.title == self.title
self.assertEqual(location.thumb_width, self.thumb_width) assert inline_query_result_location.thumb_url == self.thumb_url
self.assertEqual(location.thumb_height, self.thumb_height) assert inline_query_result_location.thumb_width == self.thumb_width
self.assertDictEqual(location.input_message_content.to_dict(), assert inline_query_result_location.thumb_height == self.thumb_height
self.input_message_content.to_dict()) assert inline_query_result_location.input_message_content.to_dict() == \
self.assertDictEqual(location.reply_markup.to_dict(), self.reply_markup.to_dict()) self.input_message_content.to_dict()
assert inline_query_result_location.reply_markup.to_dict() == self.reply_markup.to_dict()
def test_location_to_json(self): def test_to_dict(self, inline_query_result_location):
location = telegram.InlineQueryResultLocation.de_json(self.json_dict, self._bot) inline_query_result_location_dict = inline_query_result_location.to_dict()
self.assertTrue(self.is_json(location.to_json())) assert isinstance(inline_query_result_location_dict, dict)
assert inline_query_result_location_dict['id'] == inline_query_result_location.id
def test_location_to_dict(self): assert inline_query_result_location_dict['type'] == inline_query_result_location.type
location = telegram.InlineQueryResultLocation.de_json(self.json_dict, self._bot).to_dict() assert inline_query_result_location_dict['latitude'] == \
inline_query_result_location.latitude
self.assertTrue(self.is_dict(location)) assert inline_query_result_location_dict['longitude'] == \
self.assertDictEqual(self.json_dict, location) inline_query_result_location.longitude
assert inline_query_result_location_dict['title'] == inline_query_result_location.title
assert inline_query_result_location_dict['thumb_url'] == \
inline_query_result_location.thumb_url
assert inline_query_result_location_dict['thumb_width'] == \
inline_query_result_location.thumb_width
assert inline_query_result_location_dict['thumb_height'] == \
inline_query_result_location.thumb_height
assert inline_query_result_location_dict['input_message_content'] == \
inline_query_result_location.input_message_content.to_dict()
assert inline_query_result_location_dict['reply_markup'] == \
inline_query_result_location.reply_markup.to_dict()
def test_equality(self): def test_equality(self):
a = telegram.InlineQueryResultLocation(self._id, self.longitude, self.latitude, self.title) a = InlineQueryResultLocation(self.id, self.longitude, self.latitude, self.title)
b = telegram.InlineQueryResultLocation(self._id, self.longitude, self.latitude, self.title) b = InlineQueryResultLocation(self.id, self.longitude, self.latitude, self.title)
c = telegram.InlineQueryResultLocation(self._id, 0, self.latitude, self.title) c = InlineQueryResultLocation(self.id, 0, self.latitude, self.title)
d = telegram.InlineQueryResultLocation("", self.longitude, self.latitude, self.title) d = InlineQueryResultLocation('', self.longitude, self.latitude, self.title)
e = telegram.InlineQueryResultArticle(self._id, "", "") e = InlineQueryResultVoice(self.id, '', '')
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertEqual(a, c) assert a == c
self.assertEqual(hash(a), hash(c)) assert hash(a) == hash(c)
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
self.assertNotEqual(a, e) assert a != e
self.assertNotEqual(hash(a), hash(e)) assert hash(a) != hash(e)
if __name__ == '__main__':
unittest.main()

View file

@ -5,107 +5,105 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
InlineQueryResultMpeg4Gif"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import (InlineQueryResultMpeg4Gif, InlineKeyboardButton, InlineQueryResultVoice,
InlineKeyboardMarkup, InputTextMessageContent)
import telegram
from tests.base import BaseTest
class InlineQueryResultMpeg4GifTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram InlineQueryResultMpeg4Gif.""" def inline_query_result_mpeg4_gif():
return InlineQueryResultMpeg4Gif(TestInlineQueryResultMpeg4Gif.id,
TestInlineQueryResultMpeg4Gif.mpeg4_url,
TestInlineQueryResultMpeg4Gif.thumb_url,
mpeg4_width=TestInlineQueryResultMpeg4Gif.mpeg4_width,
mpeg4_height=TestInlineQueryResultMpeg4Gif.mpeg4_height,
mpeg4_duration=TestInlineQueryResultMpeg4Gif.mpeg4_duration,
title=TestInlineQueryResultMpeg4Gif.title,
caption=TestInlineQueryResultMpeg4Gif.caption,
input_message_content=TestInlineQueryResultMpeg4Gif.input_message_content,
reply_markup=TestInlineQueryResultMpeg4Gif.reply_markup)
def setUp(self):
self._id = 'id'
self.type = 'mpeg4_gif'
self.mpeg4_url = 'mpeg4 url'
self.mpeg4_width = 10
self.mpeg4_height = 15
self.mpeg4_duration = 1
self.thumb_url = 'thumb url'
self.title = 'title'
self.caption = 'caption'
self.input_message_content = telegram.InputTextMessageContent('input_message_content')
self.reply_markup = telegram.InlineKeyboardMarkup(
[[telegram.InlineKeyboardButton('reply_markup')]])
self.json_dict = { class TestInlineQueryResultMpeg4Gif(object):
'type': self.type, id = 'id'
'id': self._id, type = 'mpeg4_gif'
'mpeg4_url': self.mpeg4_url, mpeg4_url = 'mpeg4 url'
'mpeg4_width': self.mpeg4_width, mpeg4_width = 10
'mpeg4_height': self.mpeg4_height, mpeg4_height = 15
'mpeg4_duration': self.mpeg4_duration, mpeg4_duration = 1
'thumb_url': self.thumb_url, thumb_url = 'thumb url'
'title': self.title, title = 'title'
'caption': self.caption, caption = 'caption'
'input_message_content': self.input_message_content.to_dict(), input_message_content = InputTextMessageContent('input_message_content')
'reply_markup': self.reply_markup.to_dict(), reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton('reply_markup')]])
}
def test_mpeg4_de_json(self): def test_expected_values(self, inline_query_result_mpeg4_gif):
mpeg4 = telegram.InlineQueryResultMpeg4Gif.de_json(self.json_dict, self._bot) assert inline_query_result_mpeg4_gif.type == self.type
assert inline_query_result_mpeg4_gif.id == self.id
assert inline_query_result_mpeg4_gif.mpeg4_url == self.mpeg4_url
assert inline_query_result_mpeg4_gif.mpeg4_width == self.mpeg4_width
assert inline_query_result_mpeg4_gif.mpeg4_height == self.mpeg4_height
assert inline_query_result_mpeg4_gif.mpeg4_duration == self.mpeg4_duration
assert inline_query_result_mpeg4_gif.thumb_url == self.thumb_url
assert inline_query_result_mpeg4_gif.title == self.title
assert inline_query_result_mpeg4_gif.caption == self.caption
assert inline_query_result_mpeg4_gif.input_message_content.to_dict() == \
self.input_message_content.to_dict()
assert inline_query_result_mpeg4_gif.reply_markup.to_dict() == self.reply_markup.to_dict()
self.assertEqual(mpeg4.type, self.type) def test_to_dict(self, inline_query_result_mpeg4_gif):
self.assertEqual(mpeg4.id, self._id) inline_query_result_mpeg4_gif_dict = inline_query_result_mpeg4_gif.to_dict()
self.assertEqual(mpeg4.mpeg4_url, self.mpeg4_url)
self.assertEqual(mpeg4.mpeg4_width, self.mpeg4_width)
self.assertEqual(mpeg4.mpeg4_height, self.mpeg4_height)
self.assertEqual(mpeg4.mpeg4_duration, self.mpeg4_duration)
self.assertEqual(mpeg4.thumb_url, self.thumb_url)
self.assertEqual(mpeg4.title, self.title)
self.assertEqual(mpeg4.caption, self.caption)
self.assertDictEqual(mpeg4.input_message_content.to_dict(),
self.input_message_content.to_dict())
self.assertDictEqual(mpeg4.reply_markup.to_dict(), self.reply_markup.to_dict())
def test_mpeg4_to_json(self): assert isinstance(inline_query_result_mpeg4_gif_dict, dict)
mpeg4 = telegram.InlineQueryResultMpeg4Gif.de_json(self.json_dict, self._bot) assert inline_query_result_mpeg4_gif_dict['type'] == inline_query_result_mpeg4_gif.type
assert inline_query_result_mpeg4_gif_dict['id'] == inline_query_result_mpeg4_gif.id
self.assertTrue(self.is_json(mpeg4.to_json())) assert inline_query_result_mpeg4_gif_dict['mpeg4_url'] == \
inline_query_result_mpeg4_gif.mpeg4_url
def test_mpeg4_to_dict(self): assert inline_query_result_mpeg4_gif_dict['mpeg4_width'] == \
mpeg4 = telegram.InlineQueryResultMpeg4Gif.de_json(self.json_dict, self._bot).to_dict() inline_query_result_mpeg4_gif.mpeg4_width
assert inline_query_result_mpeg4_gif_dict['mpeg4_height'] == \
self.assertTrue(self.is_dict(mpeg4)) inline_query_result_mpeg4_gif.mpeg4_height
self.assertDictEqual(self.json_dict, mpeg4) assert inline_query_result_mpeg4_gif_dict['mpeg4_duration'] == \
inline_query_result_mpeg4_gif.mpeg4_duration
assert inline_query_result_mpeg4_gif_dict['thumb_url'] == \
inline_query_result_mpeg4_gif.thumb_url
assert inline_query_result_mpeg4_gif_dict['title'] == inline_query_result_mpeg4_gif.title
assert inline_query_result_mpeg4_gif_dict['caption'] == \
inline_query_result_mpeg4_gif.caption
assert inline_query_result_mpeg4_gif_dict['input_message_content'] == \
inline_query_result_mpeg4_gif.input_message_content.to_dict()
assert inline_query_result_mpeg4_gif_dict['reply_markup'] == \
inline_query_result_mpeg4_gif.reply_markup.to_dict()
def test_equality(self): def test_equality(self):
a = telegram.InlineQueryResultMpeg4Gif(self._id, self.mpeg4_url, self.thumb_url) a = InlineQueryResultMpeg4Gif(self.id, self.mpeg4_url, self.thumb_url)
b = telegram.InlineQueryResultMpeg4Gif(self._id, self.mpeg4_url, self.thumb_url) b = InlineQueryResultMpeg4Gif(self.id, self.mpeg4_url, self.thumb_url)
c = telegram.InlineQueryResultMpeg4Gif(self._id, "", self.thumb_url) c = InlineQueryResultMpeg4Gif(self.id, '', self.thumb_url)
d = telegram.InlineQueryResultMpeg4Gif("", self.mpeg4_url, self.thumb_url) d = InlineQueryResultMpeg4Gif('', self.mpeg4_url, self.thumb_url)
e = telegram.InlineQueryResultArticle(self._id, "", "") e = InlineQueryResultVoice(self.id, '', '')
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertEqual(a, c) assert a == c
self.assertEqual(hash(a), hash(c)) assert hash(a) == hash(c)
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
self.assertNotEqual(a, e) assert a != e
self.assertNotEqual(hash(a), hash(e)) assert hash(a) != hash(e)
if __name__ == '__main__':
unittest.main()

View file

@ -5,107 +5,102 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
InlineQueryResultPhoto"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import (InputTextMessageContent, InlineKeyboardButton, InlineKeyboardMarkup,
InlineQueryResultPhoto, InlineQueryResultVoice)
import telegram
from tests.base import BaseTest
class InlineQueryResultPhotoTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram InlineQueryResultPhoto.""" def inline_query_result_photo():
return InlineQueryResultPhoto(TestInlineQueryResultPhoto.id,
TestInlineQueryResultPhoto.photo_url,
TestInlineQueryResultPhoto.thumb_url,
photo_width=TestInlineQueryResultPhoto.photo_width,
photo_height=TestInlineQueryResultPhoto.photo_height,
title=TestInlineQueryResultPhoto.title,
description=TestInlineQueryResultPhoto.description,
caption=TestInlineQueryResultPhoto.caption,
input_message_content=TestInlineQueryResultPhoto.input_message_content,
reply_markup=TestInlineQueryResultPhoto.reply_markup)
def setUp(self):
self._id = 'id'
self.type = 'photo'
self.photo_url = 'photo url'
self.photo_width = 10
self.photo_height = 15
self.thumb_url = 'thumb url'
self.title = 'title'
self.description = 'description'
self.caption = 'caption'
self.input_message_content = telegram.InputTextMessageContent('input_message_content')
self.reply_markup = telegram.InlineKeyboardMarkup(
[[telegram.InlineKeyboardButton('reply_markup')]])
self.json_dict = { class TestInlineQueryResultPhoto(object):
'type': self.type, id = 'id'
'id': self._id, type = 'photo'
'photo_url': self.photo_url, photo_url = 'photo url'
'photo_width': self.photo_width, photo_width = 10
'photo_height': self.photo_height, photo_height = 15
'thumb_url': self.thumb_url, thumb_url = 'thumb url'
'title': self.title, title = 'title'
'description': self.description, description = 'description'
'caption': self.caption, caption = 'caption'
'input_message_content': self.input_message_content.to_dict(), input_message_content = InputTextMessageContent('input_message_content')
'reply_markup': self.reply_markup.to_dict(), reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton('reply_markup')]])
}
def test_photo_de_json(self): def test_expected_values(self, inline_query_result_photo):
photo = telegram.InlineQueryResultPhoto.de_json(self.json_dict, self._bot) assert inline_query_result_photo.type == self.type
assert inline_query_result_photo.id == self.id
assert inline_query_result_photo.photo_url == self.photo_url
assert inline_query_result_photo.photo_width == self.photo_width
assert inline_query_result_photo.photo_height == self.photo_height
assert inline_query_result_photo.thumb_url == self.thumb_url
assert inline_query_result_photo.title == self.title
assert inline_query_result_photo.description == self.description
assert inline_query_result_photo.caption == self.caption
assert inline_query_result_photo.input_message_content.to_dict() == \
self.input_message_content.to_dict()
assert inline_query_result_photo.reply_markup.to_dict() == self.reply_markup.to_dict()
self.assertEqual(photo.type, self.type) def test_to_dict(self, inline_query_result_photo):
self.assertEqual(photo.id, self._id) inline_query_result_photo_dict = inline_query_result_photo.to_dict()
self.assertEqual(photo.photo_url, self.photo_url)
self.assertEqual(photo.photo_width, self.photo_width)
self.assertEqual(photo.photo_height, self.photo_height)
self.assertEqual(photo.thumb_url, self.thumb_url)
self.assertEqual(photo.title, self.title)
self.assertEqual(photo.description, self.description)
self.assertEqual(photo.caption, self.caption)
self.assertDictEqual(photo.input_message_content.to_dict(),
self.input_message_content.to_dict())
self.assertDictEqual(photo.reply_markup.to_dict(), self.reply_markup.to_dict())
def test_photo_to_json(self): assert isinstance(inline_query_result_photo_dict, dict)
photo = telegram.InlineQueryResultPhoto.de_json(self.json_dict, self._bot) assert inline_query_result_photo_dict['type'] == inline_query_result_photo.type
assert inline_query_result_photo_dict['id'] == inline_query_result_photo.id
self.assertTrue(self.is_json(photo.to_json())) assert inline_query_result_photo_dict['photo_url'] == inline_query_result_photo.photo_url
assert inline_query_result_photo_dict['photo_width'] == \
def test_photo_to_dict(self): inline_query_result_photo.photo_width
photo = telegram.InlineQueryResultPhoto.de_json(self.json_dict, self._bot).to_dict() assert inline_query_result_photo_dict['photo_height'] == \
inline_query_result_photo.photo_height
self.assertTrue(self.is_dict(photo)) assert inline_query_result_photo_dict['thumb_url'] == inline_query_result_photo.thumb_url
self.assertDictEqual(self.json_dict, photo) assert inline_query_result_photo_dict['title'] == inline_query_result_photo.title
assert inline_query_result_photo_dict['description'] == \
inline_query_result_photo.description
assert inline_query_result_photo_dict['caption'] == inline_query_result_photo.caption
assert inline_query_result_photo_dict['input_message_content'] == \
inline_query_result_photo.input_message_content.to_dict()
assert inline_query_result_photo_dict['reply_markup'] == \
inline_query_result_photo.reply_markup.to_dict()
def test_equality(self): def test_equality(self):
a = telegram.InlineQueryResultPhoto(self._id, self.photo_url, self.thumb_url) a = InlineQueryResultPhoto(self.id, self.photo_url, self.thumb_url)
b = telegram.InlineQueryResultPhoto(self._id, self.photo_url, self.thumb_url) b = InlineQueryResultPhoto(self.id, self.photo_url, self.thumb_url)
c = telegram.InlineQueryResultPhoto(self._id, "", self.thumb_url) c = InlineQueryResultPhoto(self.id, '', self.thumb_url)
d = telegram.InlineQueryResultPhoto("", self.photo_url, self.thumb_url) d = InlineQueryResultPhoto('', self.photo_url, self.thumb_url)
e = telegram.InlineQueryResultArticle(self._id, "", "") e = InlineQueryResultVoice(self.id, '', '')
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertEqual(a, c) assert a == c
self.assertEqual(hash(a), hash(c)) assert hash(a) == hash(c)
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
self.assertNotEqual(a, e) assert a != e
self.assertNotEqual(hash(a), hash(e)) assert hash(a) != hash(e)
if __name__ == '__main__':
unittest.main()

View file

@ -5,112 +5,109 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
InlineQueryResultVenue"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import (InlineQueryResultVoice, InputTextMessageContent, InlineKeyboardButton,
InlineQueryResultVenue, InlineKeyboardMarkup)
import telegram
from tests.base import BaseTest
class InlineQueryResultVenueTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram InlineQueryResultVenue.""" def inline_query_result_venue():
return InlineQueryResultVenue(TestInlineQueryResultVenue.id,
TestInlineQueryResultVenue.latitude,
TestInlineQueryResultVenue.longitude,
TestInlineQueryResultVenue.title,
TestInlineQueryResultVenue.address,
foursquare_id=TestInlineQueryResultVenue.foursquare_id,
thumb_url=TestInlineQueryResultVenue.thumb_url,
thumb_width=TestInlineQueryResultVenue.thumb_width,
thumb_height=TestInlineQueryResultVenue.thumb_height,
input_message_content=TestInlineQueryResultVenue.input_message_content,
reply_markup=TestInlineQueryResultVenue.reply_markup)
def setUp(self):
self._id = 'id'
self.type = 'venue'
self.latitude = 'latitude'
self.longitude = 'longitude'
self.title = 'title'
self._address = 'address' # nose binds self.address for testing
self.foursquare_id = 'foursquare id'
self.thumb_url = 'thumb url'
self.thumb_width = 10
self.thumb_height = 15
self.input_message_content = telegram.InputTextMessageContent('input_message_content')
self.reply_markup = telegram.InlineKeyboardMarkup(
[[telegram.InlineKeyboardButton('reply_markup')]])
self.json_dict = {
'id': self._id,
'type': self.type,
'latitude': self.latitude,
'longitude': self.longitude,
'title': self.title,
'address': self._address,
'foursquare_id': self.foursquare_id,
'thumb_url': self.thumb_url,
'thumb_width': self.thumb_width,
'thumb_height': self.thumb_height,
'input_message_content': self.input_message_content.to_dict(),
'reply_markup': self.reply_markup.to_dict(),
}
def test_venue_de_json(self): class TestInlineQueryResultVenue(object):
venue = telegram.InlineQueryResultVenue.de_json(self.json_dict, self._bot) id = 'id'
type = 'venue'
latitude = 'latitude'
longitude = 'longitude'
title = 'title'
address = 'address'
foursquare_id = 'foursquare id'
thumb_url = 'thumb url'
thumb_width = 10
thumb_height = 15
input_message_content = InputTextMessageContent('input_message_content')
reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton('reply_markup')]])
self.assertEqual(venue.id, self._id) def test_expected_values(self, inline_query_result_venue):
self.assertEqual(venue.type, self.type) assert inline_query_result_venue.id == self.id
self.assertEqual(venue.latitude, self.latitude) assert inline_query_result_venue.type == self.type
self.assertEqual(venue.longitude, self.longitude) assert inline_query_result_venue.latitude == self.latitude
self.assertEqual(venue.title, self.title) assert inline_query_result_venue.longitude == self.longitude
self.assertEqual(venue.address, self._address) assert inline_query_result_venue.title == self.title
self.assertEqual(venue.foursquare_id, self.foursquare_id) assert inline_query_result_venue.address == self.address
self.assertEqual(venue.thumb_url, self.thumb_url) assert inline_query_result_venue.foursquare_id == self.foursquare_id
self.assertEqual(venue.thumb_width, self.thumb_width) assert inline_query_result_venue.thumb_url == self.thumb_url
self.assertEqual(venue.thumb_height, self.thumb_height) assert inline_query_result_venue.thumb_width == self.thumb_width
self.assertDictEqual(venue.input_message_content.to_dict(), assert inline_query_result_venue.thumb_height == self.thumb_height
self.input_message_content.to_dict()) assert inline_query_result_venue.input_message_content.to_dict() == \
self.assertDictEqual(venue.reply_markup.to_dict(), self.reply_markup.to_dict()) self.input_message_content.to_dict()
assert inline_query_result_venue.reply_markup.to_dict() == self.reply_markup.to_dict()
def test_venue_to_json(self): def test_to_dict(self, inline_query_result_venue):
venue = telegram.InlineQueryResultVenue.de_json(self.json_dict, self._bot) inline_query_result_venue_dict = inline_query_result_venue.to_dict()
self.assertTrue(self.is_json(venue.to_json())) assert isinstance(inline_query_result_venue_dict, dict)
assert inline_query_result_venue_dict['id'] == inline_query_result_venue.id
def test_venue_to_dict(self): assert inline_query_result_venue_dict['type'] == inline_query_result_venue.type
venue = telegram.InlineQueryResultVenue.de_json(self.json_dict, self._bot).to_dict() assert inline_query_result_venue_dict['latitude'] == inline_query_result_venue.latitude
assert inline_query_result_venue_dict['longitude'] == inline_query_result_venue.longitude
self.assertTrue(self.is_dict(venue)) assert inline_query_result_venue_dict['title'] == inline_query_result_venue.title
self.assertDictEqual(self.json_dict, venue) assert inline_query_result_venue_dict['address'] == inline_query_result_venue.address
assert inline_query_result_venue_dict['foursquare_id'] == \
inline_query_result_venue.foursquare_id
assert inline_query_result_venue_dict['thumb_url'] == inline_query_result_venue.thumb_url
assert inline_query_result_venue_dict['thumb_width'] == \
inline_query_result_venue.thumb_width
assert inline_query_result_venue_dict['thumb_height'] == \
inline_query_result_venue.thumb_height
assert inline_query_result_venue_dict['input_message_content'] == \
inline_query_result_venue.input_message_content.to_dict()
assert inline_query_result_venue_dict['reply_markup'] == \
inline_query_result_venue.reply_markup.to_dict()
def test_equality(self): def test_equality(self):
a = telegram.InlineQueryResultVenue(self._id, self.longitude, self.latitude, self.title, a = InlineQueryResultVenue(self.id, self.longitude, self.latitude, self.title,
self._address) self.address)
b = telegram.InlineQueryResultVenue(self._id, self.longitude, self.latitude, self.title, b = InlineQueryResultVenue(self.id, self.longitude, self.latitude, self.title,
self._address) self.address)
c = telegram.InlineQueryResultVenue(self._id, "", self.latitude, self.title, self._address) c = InlineQueryResultVenue(self.id, '', self.latitude, self.title, self.address)
d = telegram.InlineQueryResultVenue("", self.longitude, self.latitude, self.title, d = InlineQueryResultVenue('', self.longitude, self.latitude, self.title,
self._address) self.address)
e = telegram.InlineQueryResultArticle(self._id, "", "") e = InlineQueryResultVoice(self.id, '', '')
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertEqual(a, c) assert a == c
self.assertEqual(hash(a), hash(c)) assert hash(a) == hash(c)
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
self.assertNotEqual(a, e) assert a != e
self.assertNotEqual(hash(a), hash(e)) assert hash(a) != hash(e)
if __name__ == '__main__':
unittest.main()

View file

@ -5,117 +5,115 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
InlineQueryResultVideo"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import (InlineKeyboardButton, InputTextMessageContent, InlineQueryResultVideo,
InlineKeyboardMarkup, InlineQueryResultVoice)
import telegram
from tests.base import BaseTest
class InlineQueryResultVideoTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram InlineQueryResultVideo.""" def inline_query_result_video():
return InlineQueryResultVideo(TestInlineQueryResultVideo.id,
TestInlineQueryResultVideo.video_url,
TestInlineQueryResultVideo.mime_type,
TestInlineQueryResultVideo.thumb_url,
TestInlineQueryResultVideo.title,
video_width=TestInlineQueryResultVideo.video_width,
video_height=TestInlineQueryResultVideo.video_height,
video_duration=TestInlineQueryResultVideo.video_duration,
caption=TestInlineQueryResultVideo.caption,
description=TestInlineQueryResultVideo.description,
input_message_content=TestInlineQueryResultVideo.input_message_content,
reply_markup=TestInlineQueryResultVideo.reply_markup)
def setUp(self):
self._id = 'id'
self.type = 'video'
self.video_url = 'video url'
self.mime_type = 'mime type'
self.video_width = 10
self.video_height = 15
self.video_duration = 15
self.thumb_url = 'thumb url'
self.title = 'title'
self.caption = 'caption'
self.description = 'description'
self.input_message_content = telegram.InputTextMessageContent('input_message_content')
self.reply_markup = telegram.InlineKeyboardMarkup(
[[telegram.InlineKeyboardButton('reply_markup')]])
self.json_dict = { class TestInlineQueryResultVideo(object):
'type': self.type, id = 'id'
'id': self._id, type = 'video'
'video_url': self.video_url, video_url = 'video url'
'mime_type': self.mime_type, mime_type = 'mime type'
'video_width': self.video_width, video_width = 10
'video_height': self.video_height, video_height = 15
'video_duration': self.video_duration, video_duration = 15
'thumb_url': self.thumb_url, thumb_url = 'thumb url'
'title': self.title, title = 'title'
'caption': self.caption, caption = 'caption'
'description': self.description, description = 'description'
'input_message_content': self.input_message_content.to_dict(), input_message_content = InputTextMessageContent('input_message_content')
'reply_markup': self.reply_markup.to_dict(), reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton('reply_markup')]])
}
def test_video_de_json(self): def test_expected_values(self, inline_query_result_video):
video = telegram.InlineQueryResultVideo.de_json(self.json_dict, self._bot) assert inline_query_result_video.type == self.type
assert inline_query_result_video.id == self.id
assert inline_query_result_video.video_url == self.video_url
assert inline_query_result_video.mime_type == self.mime_type
assert inline_query_result_video.video_width == self.video_width
assert inline_query_result_video.video_height == self.video_height
assert inline_query_result_video.video_duration == self.video_duration
assert inline_query_result_video.thumb_url == self.thumb_url
assert inline_query_result_video.title == self.title
assert inline_query_result_video.description == self.description
assert inline_query_result_video.caption == self.caption
assert inline_query_result_video.input_message_content.to_dict() == \
self.input_message_content.to_dict()
assert inline_query_result_video.reply_markup.to_dict() == self.reply_markup.to_dict()
self.assertEqual(video.type, self.type) def test_to_dict(self, inline_query_result_video):
self.assertEqual(video.id, self._id) inline_query_result_video_dict = inline_query_result_video.to_dict()
self.assertEqual(video.video_url, self.video_url)
self.assertEqual(video.mime_type, self.mime_type)
self.assertEqual(video.video_width, self.video_width)
self.assertEqual(video.video_height, self.video_height)
self.assertEqual(video.video_duration, self.video_duration)
self.assertEqual(video.thumb_url, self.thumb_url)
self.assertEqual(video.title, self.title)
self.assertEqual(video.description, self.description)
self.assertEqual(video.caption, self.caption)
self.assertDictEqual(video.input_message_content.to_dict(),
self.input_message_content.to_dict())
self.assertDictEqual(video.reply_markup.to_dict(), self.reply_markup.to_dict())
def test_video_to_json(self): assert isinstance(inline_query_result_video_dict, dict)
video = telegram.InlineQueryResultVideo.de_json(self.json_dict, self._bot) assert inline_query_result_video_dict['type'] == inline_query_result_video.type
assert inline_query_result_video_dict['id'] == inline_query_result_video.id
self.assertTrue(self.is_json(video.to_json())) assert inline_query_result_video_dict['video_url'] == inline_query_result_video.video_url
assert inline_query_result_video_dict['mime_type'] == inline_query_result_video.mime_type
def test_video_to_dict(self): assert inline_query_result_video_dict['video_width'] == \
video = telegram.InlineQueryResultVideo.de_json(self.json_dict, self._bot).to_dict() inline_query_result_video.video_width
assert inline_query_result_video_dict['video_height'] == \
self.assertTrue(self.is_dict(video)) inline_query_result_video.video_height
self.assertDictEqual(self.json_dict, video) assert inline_query_result_video_dict['video_duration'] == \
inline_query_result_video.video_duration
assert inline_query_result_video_dict['thumb_url'] == inline_query_result_video.thumb_url
assert inline_query_result_video_dict['title'] == inline_query_result_video.title
assert inline_query_result_video_dict['description'] == \
inline_query_result_video.description
assert inline_query_result_video_dict['caption'] == inline_query_result_video.caption
assert inline_query_result_video_dict['input_message_content'] == \
inline_query_result_video.input_message_content.to_dict()
assert inline_query_result_video_dict['reply_markup'] == \
inline_query_result_video.reply_markup.to_dict()
def test_equality(self): def test_equality(self):
a = telegram.InlineQueryResultVideo(self._id, self.video_url, self.mime_type, a = InlineQueryResultVideo(self.id, self.video_url, self.mime_type,
self.thumb_url, self.title) self.thumb_url, self.title)
b = telegram.InlineQueryResultVideo(self._id, self.video_url, self.mime_type, b = InlineQueryResultVideo(self.id, self.video_url, self.mime_type,
self.thumb_url, self.title) self.thumb_url, self.title)
c = telegram.InlineQueryResultVideo(self._id, "", self.mime_type, self.thumb_url, c = InlineQueryResultVideo(self.id, '', self.mime_type, self.thumb_url,
self.title) self.title)
d = telegram.InlineQueryResultVideo("", self.video_url, self.mime_type, self.thumb_url, d = InlineQueryResultVideo('', self.video_url, self.mime_type, self.thumb_url,
self.title) self.title)
e = telegram.InlineQueryResultArticle(self._id, "", "") e = InlineQueryResultVoice(self.id, '', '')
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertEqual(a, c) assert a == c
self.assertEqual(hash(a), hash(c)) assert hash(a) == hash(c)
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
self.assertNotEqual(a, e) assert a != e
self.assertNotEqual(hash(a), hash(e)) assert hash(a) != hash(e)
if __name__ == '__main__':
unittest.main()

View file

@ -5,98 +5,89 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
InlineQueryResultVoice"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import (InlineKeyboardButton, InputTextMessageContent, InlineQueryResultAudio,
InlineQueryResultVoice, InlineKeyboardMarkup)
import telegram
from tests.base import BaseTest
class InlineQueryResultVoiceTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram InlineQueryResultVoice.""" def inline_query_result_voice():
return InlineQueryResultVoice(type=TestInlineQueryResultVoice.type,
id=TestInlineQueryResultVoice.id,
voice_url=TestInlineQueryResultVoice.voice_url,
title=TestInlineQueryResultVoice.title,
voice_duration=TestInlineQueryResultVoice.voice_duration,
caption=TestInlineQueryResultVoice.caption,
input_message_content=TestInlineQueryResultVoice.input_message_content,
reply_markup=TestInlineQueryResultVoice.reply_markup)
def setUp(self):
self._id = 'id'
self.type = 'voice'
self.voice_url = 'voice url'
self.title = 'title'
self.voice_duration = 'voice_duration'
self.caption = 'caption'
self.input_message_content = telegram.InputTextMessageContent('input_message_content')
self.reply_markup = telegram.InlineKeyboardMarkup(
[[telegram.InlineKeyboardButton('reply_markup')]])
self.json_dict = { class TestInlineQueryResultVoice(object):
'type': self.type, id = 'id'
'id': self._id, type = 'voice'
'voice_url': self.voice_url, voice_url = 'voice url'
'title': self.title, title = 'title'
'voice_duration': self.voice_duration, voice_duration = 'voice_duration'
'caption': self.caption, caption = 'caption'
'input_message_content': self.input_message_content.to_dict(), input_message_content = InputTextMessageContent('input_message_content')
'reply_markup': self.reply_markup.to_dict(), reply_markup = InlineKeyboardMarkup([[InlineKeyboardButton('reply_markup')]])
}
def test_voice_de_json(self): def test_expected_values(self, inline_query_result_voice):
voice = telegram.InlineQueryResultVoice.de_json(self.json_dict, self._bot) assert inline_query_result_voice.type == self.type
assert inline_query_result_voice.id == self.id
assert inline_query_result_voice.voice_url == self.voice_url
assert inline_query_result_voice.title == self.title
assert inline_query_result_voice.voice_duration == self.voice_duration
assert inline_query_result_voice.caption == self.caption
assert inline_query_result_voice.input_message_content.to_dict() == \
self.input_message_content.to_dict()
assert inline_query_result_voice.reply_markup.to_dict() == self.reply_markup.to_dict()
self.assertEqual(voice.type, self.type) def test_to_dict(self, inline_query_result_voice):
self.assertEqual(voice.id, self._id) inline_query_result_voice_dict = inline_query_result_voice.to_dict()
self.assertEqual(voice.voice_url, self.voice_url)
self.assertEqual(voice.title, self.title)
self.assertEqual(voice.voice_duration, self.voice_duration)
self.assertEqual(voice.caption, self.caption)
self.assertDictEqual(voice.input_message_content.to_dict(),
self.input_message_content.to_dict())
self.assertDictEqual(voice.reply_markup.to_dict(), self.reply_markup.to_dict())
def test_voice_to_json(self): assert isinstance(inline_query_result_voice_dict, dict)
voice = telegram.InlineQueryResultVoice.de_json(self.json_dict, self._bot) assert inline_query_result_voice_dict['type'] == inline_query_result_voice.type
assert inline_query_result_voice_dict['id'] == inline_query_result_voice.id
self.assertTrue(self.is_json(voice.to_json())) assert inline_query_result_voice_dict['voice_url'] == inline_query_result_voice.voice_url
assert inline_query_result_voice_dict['title'] == inline_query_result_voice.title
def test_voice_to_dict(self): assert inline_query_result_voice_dict['voice_duration'] == \
voice = telegram.InlineQueryResultVoice.de_json(self.json_dict, self._bot).to_dict() inline_query_result_voice.voice_duration
assert inline_query_result_voice_dict['caption'] == inline_query_result_voice.caption
self.assertTrue(self.is_dict(voice)) assert inline_query_result_voice_dict['input_message_content'] == \
self.assertDictEqual(self.json_dict, voice) inline_query_result_voice.input_message_content.to_dict()
assert inline_query_result_voice_dict['reply_markup'] == \
inline_query_result_voice.reply_markup.to_dict()
def test_equality(self): def test_equality(self):
a = telegram.InlineQueryResultVoice(self._id, self.voice_url, self.title) a = InlineQueryResultVoice(self.id, self.voice_url, self.title)
b = telegram.InlineQueryResultVoice(self._id, self.voice_url, self.title) b = InlineQueryResultVoice(self.id, self.voice_url, self.title)
c = telegram.InlineQueryResultVoice(self._id, "", self.title) c = InlineQueryResultVoice(self.id, '', self.title)
d = telegram.InlineQueryResultVoice("", self.voice_url, self.title) d = InlineQueryResultVoice('', self.voice_url, self.title)
e = telegram.InlineQueryResultArticle(self._id, "", "") e = InlineQueryResultAudio(self.id, '', '')
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertEqual(a, c) assert a == c
self.assertEqual(hash(a), hash(c)) assert hash(a) == hash(c)
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
self.assertNotEqual(a, e) assert a != e
self.assertNotEqual(hash(a), hash(e)) assert hash(a) != hash(e)
if __name__ == '__main__':
unittest.main()

View file

@ -5,76 +5,71 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
InputContactMessageContent"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import InputContactMessageContent, InputMessageContent
import telegram
from tests.base import BaseTest
class InputContactMessageContentTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='function')
"""This object represents Tests for Telegram InputContactMessageContent.""" def json_dict():
return {
def setUp(self): 'first_name': TestInputContactMessageContent.first_name,
self.phone_number = 'phone number' 'phone_number': TestInputContactMessageContent.phone_number,
self.first_name = 'first name' 'last_name': TestInputContactMessageContent.last_name,
self.last_name = 'last name'
self.json_dict = {
'first_name': self.first_name,
'phone_number': self.phone_number,
'last_name': self.last_name,
} }
def test_icmc_de_json(self):
icmc = telegram.InputContactMessageContent.de_json(self.json_dict, self._bot)
self.assertEqual(icmc.first_name, self.first_name) @pytest.fixture(scope='class')
self.assertEqual(icmc.phone_number, self.phone_number) def input_contact_message_content():
self.assertEqual(icmc.last_name, self.last_name) return InputContactMessageContent(TestInputContactMessageContent.phone_number,
TestInputContactMessageContent.first_name,
last_name=TestInputContactMessageContent.last_name)
def test_icmc_de_json_factory(self):
icmc = telegram.InputMessageContent.de_json(self.json_dict, self._bot)
self.assertTrue(isinstance(icmc, telegram.InputContactMessageContent)) class TestInputContactMessageContent(object):
phone_number = 'phone number'
first_name = 'first name'
last_name = 'last name'
def test_icmc_de_json_factory_without_required_args(self): def test_de_json(self, json_dict, bot):
json_dict = self.json_dict input_contact_message_content_json = InputContactMessageContent.de_json(json_dict, bot)
assert input_contact_message_content_json.first_name == self.first_name
assert input_contact_message_content_json.phone_number == self.phone_number
assert input_contact_message_content_json.last_name == self.last_name
def test_de_json_factory(self, json_dict, bot):
input_contact_message_content_json = InputMessageContent.de_json(json_dict, bot)
assert isinstance(input_contact_message_content_json, InputContactMessageContent)
def test_de_json_factory_without_required_args(self, json_dict, bot):
del (json_dict['phone_number']) del (json_dict['phone_number'])
del (json_dict['first_name']) del (json_dict['first_name'])
icmc = telegram.InputMessageContent.de_json(json_dict, self._bot) input_contact_message_content_json = InputMessageContent.de_json(json_dict, bot)
self.assertFalse(icmc) assert input_contact_message_content_json is None
def test_icmc_to_json(self): def test_to_dict(self, input_contact_message_content):
icmc = telegram.InputContactMessageContent.de_json(self.json_dict, self._bot) input_contact_message_content_dict = input_contact_message_content.to_dict()
self.assertTrue(self.is_json(icmc.to_json())) assert isinstance(input_contact_message_content_dict, dict)
assert input_contact_message_content_dict['phone_number'] == \
def test_icmc_to_dict(self): input_contact_message_content.phone_number
icmc = telegram.InputContactMessageContent.de_json(self.json_dict, self._bot).to_dict() assert input_contact_message_content_dict['first_name'] == \
input_contact_message_content.first_name
self.assertTrue(self.is_dict(icmc)) assert input_contact_message_content_dict['last_name'] == \
self.assertDictEqual(self.json_dict, icmc) input_contact_message_content.last_name
if __name__ == '__main__':
unittest.main()

View file

@ -5,74 +5,66 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
InputLocationMessageContent"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import InputMessageContent, InputLocationMessageContent
import telegram
from tests.base import BaseTest
class InputLocationMessageContentTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='function')
"""This object represents Tests for Telegram InputLocationMessageContent.""" def json_dict():
return {
def setUp(self): 'longitude': TestInputLocationMessageContent.longitude,
self.latitude = 1. 'latitude': TestInputLocationMessageContent.latitude,
self.longitude = 2.
self.json_dict = {
'longitude': self.longitude,
'latitude': self.latitude,
} }
def test_ilmc_de_json(self):
ilmc = telegram.InputLocationMessageContent.de_json(self.json_dict, self._bot)
self.assertEqual(ilmc.longitude, self.longitude) @pytest.fixture(scope='class')
self.assertEqual(ilmc.latitude, self.latitude) def input_location_message_content():
return InputLocationMessageContent(TestInputLocationMessageContent.longitude,
TestInputLocationMessageContent.latitude)
def test_ilmc_de_json_factory(self):
ilmc = telegram.InputMessageContent.de_json(self.json_dict, self._bot)
self.assertTrue(isinstance(ilmc, telegram.InputLocationMessageContent)) class TestInputLocationMessageContent(object):
latitude = 1.
longitude = 2.
def test_ilmc_de_json_factory_without_required_args(self): def test_de_json(self, json_dict, bot):
json_dict = self.json_dict input_location_message_content_json = InputLocationMessageContent.de_json(json_dict, bot)
assert input_location_message_content_json.longitude == self.longitude
assert input_location_message_content_json.latitude == self.latitude
def test_input_location_message_content_json_de_json_factory(self, json_dict, bot):
input_location_message_content_json = InputMessageContent.de_json(json_dict, bot)
assert isinstance(input_location_message_content_json, InputLocationMessageContent)
def test_de_json_factory_without_required_args(self, json_dict, bot):
del (json_dict['longitude']) del (json_dict['longitude'])
# If none args are sent it will fall in a different condition # If no args are passed it will fall in a different condition
# del (json_dict['latitude']) # del (json_dict['latitude'])
ilmc = telegram.InputMessageContent.de_json(json_dict, self._bot) input_location_message_content_json = InputMessageContent.de_json(json_dict, bot)
self.assertFalse(ilmc) assert input_location_message_content_json is None
def test_ilmc_to_json(self): def test_to_dict(self, input_location_message_content):
ilmc = telegram.InputLocationMessageContent.de_json(self.json_dict, self._bot) input_location_message_content_dict = input_location_message_content.to_dict()
self.assertTrue(self.is_json(ilmc.to_json())) assert isinstance(input_location_message_content_dict, dict)
assert input_location_message_content_dict['latitude'] == \
def test_ilmc_to_dict(self): input_location_message_content.latitude
ilmc = telegram.InputLocationMessageContent.de_json(self.json_dict, self._bot).to_dict() assert input_location_message_content_dict['longitude'] == \
input_location_message_content.longitude
self.assertTrue(self.is_dict(ilmc))
self.assertDictEqual(self.json_dict, ilmc)
if __name__ == '__main__':
unittest.main()

View file

@ -5,37 +5,23 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
InputMessageContent"""
import sys from telegram import InputMessageContent
import unittest
sys.path.append('.')
import telegram
from tests.base import BaseTest
class InputMessageContentTest(BaseTest, unittest.TestCase): class TestInputMessageContent(object):
"""This object represents Tests for Telegram InputMessageContent.""" def test_de_json(self, bot):
input_message_content = InputMessageContent.de_json(None, bot)
def test_imc_de_json(self): assert input_message_content is None
imc = telegram.InputMessageContent.de_json(None, self._bot)
self.assertFalse(imc)
if __name__ == '__main__':
unittest.main()

View file

@ -5,75 +5,71 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
InputTextMessageContent"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import InputTextMessageContent, InputMessageContent, ParseMode
import telegram
from tests.base import BaseTest
class InputTextMessageContentTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='function')
"""This object represents Tests for Telegram InputTextMessageContent.""" def json_dict():
return {
def setUp(self): 'parse_mode': TestInputTextMessageContent.parse_mode,
self.message_text = '*message text*' 'message_text': TestInputTextMessageContent.message_text,
self.parse_mode = telegram.ParseMode.MARKDOWN 'disable_web_page_preview': TestInputTextMessageContent.disable_web_page_preview,
self.disable_web_page_preview = True
self.json_dict = {
'parse_mode': self.parse_mode,
'message_text': self.message_text,
'disable_web_page_preview': self.disable_web_page_preview,
} }
def test_itmc_de_json(self):
itmc = telegram.InputTextMessageContent.de_json(self.json_dict, self._bot)
self.assertEqual(itmc.parse_mode, self.parse_mode) @pytest.fixture(scope='class')
self.assertEqual(itmc.message_text, self.message_text) def input_text_message_content():
self.assertEqual(itmc.disable_web_page_preview, self.disable_web_page_preview) return InputTextMessageContent(TestInputTextMessageContent.message_text,
parse_mode=TestInputTextMessageContent.parse_mode,
disable_web_page_preview=TestInputTextMessageContent.disable_web_page_preview)
def test_itmc_de_json_factory(self):
itmc = telegram.InputMessageContent.de_json(self.json_dict, self._bot)
self.assertTrue(isinstance(itmc, telegram.InputTextMessageContent)) class TestInputTextMessageContent(object):
message_text = '*message text*'
parse_mode = ParseMode.MARKDOWN
disable_web_page_preview = True
def test_itmc_de_json_factory_without_required_args(self): def test_de_json(self, json_dict, bot):
json_dict = self.json_dict input_text_message_content_json = InputTextMessageContent.de_json(json_dict, bot)
assert input_text_message_content_json.parse_mode == self.parse_mode
assert input_text_message_content_json.message_text == self.message_text
assert input_text_message_content_json.disable_web_page_preview == \
self.disable_web_page_preview
def test_input_text_message_content_json_de_json_factory(self, json_dict, bot):
input_text_message_content_json = InputMessageContent.de_json(json_dict, bot)
assert isinstance(input_text_message_content_json, InputTextMessageContent)
def test_de_json_factory_without_required_args(self, json_dict, bot):
del (json_dict['message_text']) del (json_dict['message_text'])
itmc = telegram.InputMessageContent.de_json(json_dict, self._bot) input_text_message_content_json = InputMessageContent.de_json(json_dict, bot)
self.assertFalse(itmc) assert input_text_message_content_json is None
def test_itmc_to_json(self): def test_to_dict(self, input_text_message_content):
itmc = telegram.InputTextMessageContent.de_json(self.json_dict, self._bot) input_text_message_content_dict = input_text_message_content.to_dict()
self.assertTrue(self.is_json(itmc.to_json())) assert isinstance(input_text_message_content_dict, dict)
assert input_text_message_content_dict['message_text'] == \
def test_itmc_to_dict(self): input_text_message_content.message_text
itmc = telegram.InputTextMessageContent.de_json(self.json_dict, self._bot).to_dict() assert input_text_message_content_dict['parse_mode'] == \
input_text_message_content.parse_mode
self.assertTrue(self.is_dict(itmc)) assert input_text_message_content_dict['disable_web_page_preview'] == \
self.assertDictEqual(self.json_dict, itmc) input_text_message_content.disable_web_page_preview
if __name__ == '__main__':
unittest.main()

View file

@ -5,84 +5,85 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
InputVenueMessageContent"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import InputVenueMessageContent, InputMessageContent
import telegram
from tests.base import BaseTest
class InputVenueMessageContentTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='function')
"""This object represents Tests for Telegram InputVenueMessageContent.""" def json_dict():
return {
def setUp(self): 'longitude': TestInputVenueMessageContent.longitude,
self.latitude = 1. 'latitude': TestInputVenueMessageContent.latitude,
self.longitude = 2. 'title': TestInputVenueMessageContent.title,
self.title = 'title' 'address': TestInputVenueMessageContent.address,
self._address = 'address' # nose binds self.address for testing 'foursquare_id': TestInputVenueMessageContent.foursquare_id,
self.foursquare_id = 'foursquare id'
self.json_dict = {
'longitude': self.longitude,
'latitude': self.latitude,
'title': self.title,
'address': self._address,
'foursquare_id': self.foursquare_id,
} }
def test_ivmc_de_json(self):
ivmc = telegram.InputVenueMessageContent.de_json(self.json_dict, self._bot)
self.assertEqual(ivmc.longitude, self.longitude) @pytest.fixture(scope='class')
self.assertEqual(ivmc.latitude, self.latitude) def input_venue_message_content():
self.assertEqual(ivmc.title, self.title) return InputVenueMessageContent(TestInputVenueMessageContent.latitude,
self.assertEqual(ivmc.address, self._address) TestInputVenueMessageContent.longitude,
self.assertEqual(ivmc.foursquare_id, self.foursquare_id) TestInputVenueMessageContent.title,
TestInputVenueMessageContent.address,
foursquare_id=TestInputVenueMessageContent.foursquare_id)
def test_ivmc_de_json_factory(self):
ivmc = telegram.InputMessageContent.de_json(self.json_dict, self._bot)
self.assertTrue(isinstance(ivmc, telegram.InputVenueMessageContent)) class TestInputVenueMessageContent(object):
latitude = 1.
longitude = 2.
title = 'title'
address = 'address'
foursquare_id = 'foursquare id'
def test_ivmc_de_json_factory_without_required_args(self): def test_de_json(self, json_dict, bot):
json_dict = self.json_dict input_venue_message_content_json = InputVenueMessageContent.de_json(json_dict, bot)
assert input_venue_message_content_json.longitude == self.longitude
assert input_venue_message_content_json.latitude == self.latitude
assert input_venue_message_content_json.title == self.title
assert input_venue_message_content_json.address == self.address
assert input_venue_message_content_json.foursquare_id == self.foursquare_id
def test_de_json_factory(self, json_dict, bot):
input_venue_message_content_json = InputMessageContent.de_json(json_dict, bot)
assert isinstance(input_venue_message_content_json, InputVenueMessageContent)
def test_de_json_factory_without_required_args(self, json_dict, bot):
json_dict = json_dict
del (json_dict['longitude']) del (json_dict['longitude'])
del (json_dict['latitude']) del (json_dict['latitude'])
del (json_dict['title']) del (json_dict['title'])
del (json_dict['address']) del (json_dict['address'])
ivmc = telegram.InputMessageContent.de_json(json_dict, self._bot) input_venue_message_content_json = InputMessageContent.de_json(json_dict, bot)
self.assertFalse(ivmc) assert input_venue_message_content_json is None
def test_ivmc_to_json(self): def test_to_dict(self, input_venue_message_content):
ivmc = telegram.InputVenueMessageContent.de_json(self.json_dict, self._bot) input_venue_message_content_dict = input_venue_message_content.to_dict()
self.assertTrue(self.is_json(ivmc.to_json())) assert isinstance(input_venue_message_content_dict, dict)
assert input_venue_message_content_dict['latitude'] == \
def test_ivmc_to_dict(self): input_venue_message_content.latitude
ivmc = telegram.InputVenueMessageContent.de_json(self.json_dict, self._bot).to_dict() assert input_venue_message_content_dict['longitude'] == \
input_venue_message_content.longitude
self.assertTrue(self.is_dict(ivmc)) assert input_venue_message_content_dict['title'] == input_venue_message_content.title
self.assertDictEqual(self.json_dict, ivmc) assert input_venue_message_content_dict['address'] == input_venue_message_content.address
assert input_venue_message_content_dict['foursquare_id'] == \
input_venue_message_content.foursquare_id
if __name__ == '__main__':
unittest.main()

View file

@ -5,96 +5,86 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
Invoice"""
import sys
import unittest
import pytest
from flaky import flaky from flaky import flaky
sys.path.append('.') from telegram import LabeledPrice, Invoice
import telegram
from tests.base import BaseTest, timeout
class InvoiceTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram Invoice.""" def invoice():
return Invoice(TestInvoice.title, TestInvoice.description, TestInvoice.start_parameter,
TestInvoice.currency, TestInvoice.total_amount)
def setUp(self):
self.payload = 'payload'
self.provider_token = self._payment_provider_token
self.prices = [telegram.LabeledPrice('Fish', 100), telegram.LabeledPrice('Fish Tax', 1000)]
self.title = 'title' class TestInvoice(object):
self.description = 'description' payload = 'payload'
self.start_parameter = 'start_parameter' prices = [LabeledPrice('Fish', 100), LabeledPrice('Fish Tax', 1000)]
self.currency = 'EUR' title = 'title'
self.total_amount = sum([p.amount for p in self.prices]) description = 'description'
start_parameter = 'start_parameter'
currency = 'EUR'
total_amount = sum([p.amount for p in prices])
self.json_dict = { def test_de_json(self, bot):
'title': self.title, invoice_json = Invoice.de_json({
'description': self.description, 'title': TestInvoice.title,
'start_parameter': self.start_parameter, 'description': TestInvoice.description,
'currency': self.currency, 'start_parameter': TestInvoice.start_parameter,
'total_amount': self.total_amount 'currency': TestInvoice.currency,
} 'total_amount': TestInvoice.total_amount
}, bot)
def test_invoice_de_json(self): assert invoice_json.title == self.title
invoice = telegram.Invoice.de_json(self.json_dict, self._bot) assert invoice_json.description == self.description
assert invoice_json.start_parameter == self.start_parameter
assert invoice_json.currency == self.currency
assert invoice_json.total_amount == self.total_amount
self.assertEqual(invoice.title, self.title) def test_to_dict(self, invoice):
self.assertEqual(invoice.description, self.description) invoice_dict = invoice.to_dict()
self.assertEqual(invoice.start_parameter, self.start_parameter)
self.assertEqual(invoice.currency, self.currency)
self.assertEqual(invoice.total_amount, self.total_amount)
def test_invoice_to_json(self): assert isinstance(invoice_dict, dict)
invoice = telegram.Invoice.de_json(self.json_dict, self._bot) assert invoice_dict['title'] == invoice.title
assert invoice_dict['description'] == invoice.description
self.assertTrue(self.is_json(invoice.to_json())) assert invoice_dict['start_parameter'] == invoice.start_parameter
assert invoice_dict['currency'] == invoice.currency
def test_invoice_to_dict(self): assert invoice_dict['total_amount'] == invoice.total_amount
invoice = telegram.Invoice.de_json(self.json_dict, self._bot).to_dict()
self.assertTrue(self.is_dict(invoice))
self.assertDictEqual(self.json_dict, invoice)
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_send_invoice_required_args_only(self): def test_send_required_args_only(self, bot, chat_id, provider_token):
message = self._bot.send_invoice(self._chat_id, self.title, self.description, self.payload, message = bot.send_invoice(chat_id, self.title, self.description, self.payload,
self.provider_token, self.start_parameter, self.currency, provider_token, self.start_parameter, self.currency,
self.prices) self.prices)
invoice = message.invoice
self.assertEqual(invoice.currency, self.currency) assert message.invoice.currency == self.currency
self.assertEqual(invoice.start_parameter, self.start_parameter) assert message.invoice.start_parameter == self.start_parameter
self.assertEqual(invoice.description, self.description) assert message.invoice.description == self.description
self.assertEqual(invoice.title, self.title) assert message.invoice.title == self.title
self.assertEqual(invoice.total_amount, self.total_amount) assert message.invoice.total_amount == self.total_amount
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_send_invoice_all_args(self): def test_send_all_args(self, bot, chat_id, provider_token):
message = self._bot.send_invoice( message = bot.send_invoice(
self._chat_id, chat_id,
self.title, self.title,
self.description, self.description,
self.payload, self.payload,
self.provider_token, provider_token,
self.start_parameter, self.start_parameter,
self.currency, self.currency,
self.prices, self.prices,
@ -106,16 +96,12 @@ class InvoiceTest(BaseTest, unittest.TestCase):
photo_height=240, photo_height=240,
need_name=True, need_name=True,
need_phone_number=True, need_phone_number=True,
need_email=True,
need_shipping_address=True, need_shipping_address=True,
is_flexible=True) is_flexible=True)
invoice = message.invoice
self.assertEqual(invoice.currency, self.currency) assert message.invoice.currency == self.currency
self.assertEqual(invoice.start_parameter, self.start_parameter) assert message.invoice.start_parameter == self.start_parameter
self.assertEqual(invoice.description, self.description) assert message.invoice.description == self.description
self.assertEqual(invoice.title, self.title) assert message.invoice.title == self.title
self.assertEqual(invoice.total_amount, self.total_amount) assert message.invoice.total_amount == self.total_amount
if __name__ == '__main__':
unittest.main()

View file

@ -1,256 +1,238 @@
#!/usr/bin/env python #!/usr/bin/env python
# encoding: utf-8
# #
# A library that provides a Python interface to the Telegram Bot API # A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017 # Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""
This module contains an object that represents Tests for JobQueue
"""
import logging
import sys
import unittest
import datetime import datetime
import time import time
from math import ceil
from time import sleep from time import sleep
from tests.test_updater import MockBot import pytest
from flaky import flaky
sys.path.append('.') from telegram.ext import JobQueue, Updater, Job
from telegram.ext import JobQueue, Job, Updater
from tests.base import BaseTest
# Enable logging
root = logging.getLogger()
root.setLevel(logging.INFO)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.WARN)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
root.addHandler(ch)
class JobQueueTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='function')
""" def job_queue(bot):
This object represents Tests for Updater, Dispatcher, WebhookServer and jq = JobQueue(bot)
WebhookHandler jq.start()
""" yield jq
jq.stop()
def setUp(self):
self.jq = JobQueue(MockBot('jobqueue_test')) @flaky(10, 1) # Timings aren't quite perfect
self.jq.start() class TestJobQueue(object):
result = 0
job_time = 0
@pytest.fixture(autouse=True)
def reset(self):
self.result = 0 self.result = 0
self.job_time = 0 self.job_time = 0
def tearDown(self): def job_run_once(self, bot, job):
if self.jq is not None:
self.jq.stop()
def job1(self, bot, job):
self.result += 1 self.result += 1
def job2(self, bot, job): def job_with_exception(self, bot, job):
raise Exception("Test Error") raise Exception('Test Error')
def job3(self, bot, job): def job_remove_self(self, bot, job):
self.result += 1 self.result += 1
job.schedule_removal() job.schedule_removal()
def job4(self, bot, job): def job_run_once_with_context(self, bot, job):
self.result += job.context self.result += job.context
def job5(self, bot, job): def job_datetime_tests(self, bot, job):
self.job_time = time.time() self.job_time = time.time()
def test_basic(self): def test_run_once(self, job_queue):
self.jq.put(Job(self.job1, 0.1)) job_queue.run_once(self.job_run_once, 0.01)
sleep(1.5) sleep(0.02)
self.assertGreaterEqual(self.result, 10) assert self.result == 1
def test_job_with_context(self): def test_job_with_context(self, job_queue):
self.jq.put(Job(self.job4, 0.1, context=5)) job_queue.run_once(self.job_run_once_with_context, 0.01, context=5)
sleep(1.5) sleep(0.02)
self.assertGreaterEqual(self.result, 50) assert self.result == 5
def test_noRepeat(self): def test_run_repeating(self, job_queue):
self.jq.put(Job(self.job1, 0.1, repeat=False)) job_queue.run_repeating(self.job_run_once, 0.02)
sleep(0.5) sleep(0.05)
self.assertEqual(1, self.result) assert self.result == 2
def test_nextT(self): def test_run_repeating_first(self, job_queue):
self.jq.put(Job(self.job1, 0.1), next_t=0.5) job_queue.run_repeating(self.job_run_once, 0.05, first=0.2)
sleep(0.45)
self.assertEqual(0, self.result)
sleep(0.1)
self.assertEqual(1, self.result)
def test_multiple(self):
self.jq.put(Job(self.job1, 0.1, repeat=False))
self.jq.put(Job(self.job1, 0.2, repeat=False))
self.jq.put(Job(self.job1, 0.4))
sleep(1)
self.assertEqual(4, self.result)
def test_disabled(self):
j0 = Job(self.job1, 0.1)
j1 = Job(self.job1, 0.2)
self.jq.put(j0)
self.jq.put(Job(self.job1, 0.4))
self.jq.put(j1)
j0.enabled = False
j1.enabled = False
sleep(1)
self.assertEqual(2, self.result)
def test_schedule_removal(self):
j0 = Job(self.job1, 0.1)
j1 = Job(self.job1, 0.2)
self.jq.put(j0)
self.jq.put(Job(self.job1, 0.4))
self.jq.put(j1)
j0.schedule_removal()
j1.schedule_removal()
sleep(1)
self.assertEqual(2, self.result)
def test_schedule_removal_from_within(self):
self.jq.put(Job(self.job1, 0.4))
self.jq.put(Job(self.job3, 0.2))
sleep(1)
self.assertEqual(3, self.result)
def test_longer_first(self):
self.jq.put(Job(self.job1, 0.2, repeat=False))
self.jq.put(Job(self.job1, 0.1, repeat=False))
sleep(0.15) sleep(0.15)
self.assertEqual(1, self.result) assert self.result == 0
sleep(0.07)
assert self.result == 1
def test_error(self): def test_multiple(self, job_queue):
self.jq.put(Job(self.job2, 0.1)) job_queue.run_once(self.job_run_once, 0.01)
self.jq.put(Job(self.job1, 0.2)) job_queue.run_once(self.job_run_once, 0.02)
sleep(0.5) job_queue.run_repeating(self.job_run_once, 0.02)
self.assertEqual(2, self.result) sleep(0.055)
assert self.result == 4
def test_jobs_tuple(self): def test_disabled(self, job_queue):
self.jq.stop() j1 = job_queue.run_once(self.job_run_once, 0.1)
jobs = tuple(Job(self.job1, t) for t in range(5, 25)) j2 = job_queue.run_repeating(self.job_run_once, 0.05)
for job in jobs: j1.enabled = False
self.jq.put(job) j2.enabled = False
self.assertTupleEqual(jobs, self.jq.jobs()) sleep(0.06)
def test_inUpdater(self): assert self.result == 0
u = Updater(bot="MockBot")
j1.enabled = True
sleep(0.2)
assert self.result == 1
def test_schedule_removal(self, job_queue):
j1 = job_queue.run_once(self.job_run_once, 0.03)
j2 = job_queue.run_repeating(self.job_run_once, 0.02)
sleep(0.025)
j1.schedule_removal()
j2.schedule_removal()
sleep(0.04)
assert self.result == 1
def test_schedule_removal_from_within(self, job_queue):
job_queue.run_repeating(self.job_remove_self, 0.01)
sleep(0.05)
assert self.result == 1
def test_longer_first(self, job_queue):
job_queue.run_once(self.job_run_once, 0.02)
job_queue.run_once(self.job_run_once, 0.01)
sleep(0.015)
assert self.result == 1
def test_error(self, job_queue):
job_queue.run_repeating(self.job_with_exception, 0.01)
job_queue.run_repeating(self.job_run_once, 0.02)
sleep(0.03)
assert self.result == 1
def test_in_updater(self, bot):
u = Updater(bot=bot)
u.job_queue.start() u.job_queue.start()
try: try:
u.job_queue.put(Job(self.job1, 0.5)) u.job_queue.run_repeating(self.job_run_once, 0.02)
sleep(0.75) sleep(0.03)
self.assertEqual(1, self.result) assert self.result == 1
u.stop() u.stop()
sleep(2) sleep(1)
self.assertEqual(1, self.result) assert self.result == 1
finally: finally:
u.stop() u.stop()
def test_time_unit_int(self): def test_time_unit_int(self, job_queue):
# Testing seconds in int # Testing seconds in int
delta = 2 delta = 0.05
expected_time = time.time() + delta expected_time = time.time() + delta
self.jq.put(Job(self.job5, delta, repeat=False)) job_queue.run_once(self.job_datetime_tests, delta)
sleep(2.5) sleep(0.06)
self.assertAlmostEqual(self.job_time, expected_time, delta=0.1) assert pytest.approx(self.job_time) == expected_time
def test_time_unit_dt_timedelta(self): def test_time_unit_dt_timedelta(self, job_queue):
# Testing seconds, minutes and hours as datetime.timedelta object # Testing seconds, minutes and hours as datetime.timedelta object
# This is sufficient to test that it actually works. # This is sufficient to test that it actually works.
interval = datetime.timedelta(seconds=2) interval = datetime.timedelta(seconds=0.05)
expected_time = time.time() + interval.total_seconds() expected_time = time.time() + interval.total_seconds()
self.jq.put(Job(self.job5, interval, repeat=False)) job_queue.run_once(self.job_datetime_tests, interval)
sleep(2.5) sleep(0.06)
self.assertAlmostEqual(self.job_time, expected_time, delta=0.1) assert pytest.approx(self.job_time) == expected_time
def test_time_unit_dt_datetime(self): def test_time_unit_dt_datetime(self, job_queue):
# Testing running at a specific datetime # Testing running at a specific datetime
delta = datetime.timedelta(seconds=2) delta = datetime.timedelta(seconds=0.05)
next_t = datetime.datetime.now() + delta when = datetime.datetime.now() + delta
expected_time = time.time() + delta.total_seconds() expected_time = time.time() + delta.total_seconds()
self.jq.put(Job(self.job5, repeat=False), next_t=next_t) job_queue.run_once(self.job_datetime_tests, when)
sleep(2.5) sleep(0.06)
self.assertAlmostEqual(self.job_time, expected_time, delta=0.1) assert pytest.approx(self.job_time) == expected_time
def test_time_unit_dt_time_today(self): def test_time_unit_dt_time_today(self, job_queue):
# Testing running at a specific time today # Testing running at a specific time today
delta = 2 delta = 0.05
next_t = (datetime.datetime.now() + datetime.timedelta(seconds=delta)).time() when = (datetime.datetime.now() + datetime.timedelta(seconds=delta)).time()
expected_time = time.time() + delta expected_time = time.time() + delta
self.jq.put(Job(self.job5, repeat=False), next_t=next_t) job_queue.run_once(self.job_datetime_tests, when)
sleep(2.5) sleep(0.06)
self.assertAlmostEqual(self.job_time, expected_time, delta=0.1) assert pytest.approx(self.job_time) == expected_time
def test_time_unit_dt_time_tomorrow(self): def test_time_unit_dt_time_tomorrow(self, job_queue):
# Testing running at a specific time that has passed today. Since we can't wait a day, we # Testing running at a specific time that has passed today. Since we can't wait a day, we
# test if the jobs next_t has been calculated correctly # test if the jobs next_t has been calculated correctly
delta = -2 delta = -2
next_t = (datetime.datetime.now() + datetime.timedelta(seconds=delta)).time() when = (datetime.datetime.now() + datetime.timedelta(seconds=delta)).time()
expected_time = time.time() + delta + 60 * 60 * 24 expected_time = time.time() + delta + 60 * 60 * 24
self.jq.put(Job(self.job5, repeat=False), next_t=next_t) job_queue.run_once(self.job_datetime_tests, when)
self.assertAlmostEqual(self.jq.queue.get(False)[0], expected_time, delta=0.1) assert pytest.approx(job_queue.queue.get(False)[0]) == expected_time
def test_run_once(self): def test_run_daily(self, job_queue):
delta = 2 delta = 0.5
expected_time = time.time() + delta
self.jq.run_once(self.job5, delta)
sleep(2.5)
self.assertAlmostEqual(self.job_time, expected_time, delta=0.1)
def test_run_repeating(self):
interval = 0.1
first = 1.5
self.jq.run_repeating(self.job1, interval, first=first)
sleep(2.505)
self.assertAlmostEqual(self.result, 10, delta=1)
def test_run_daily(self):
delta = 1
time_of_day = (datetime.datetime.now() + datetime.timedelta(seconds=delta)).time() time_of_day = (datetime.datetime.now() + datetime.timedelta(seconds=delta)).time()
expected_time = time.time() + 60 * 60 * 24 + delta expected_time = time.time() + 60 * 60 * 24 + delta
self.jq.run_daily(self.job1, time_of_day) job_queue.run_daily(self.job_run_once, time_of_day)
sleep(2 * delta) sleep(0.6)
self.assertEqual(self.result, 1) assert self.result == 1
self.assertAlmostEqual(self.jq.queue.get(False)[0], expected_time, delta=0.1) assert pytest.approx(job_queue.queue.get(False)[0]) == expected_time
def test_warnings(self, job_queue):
j = Job(self.job_run_once, repeat=False)
with pytest.warns(UserWarning):
job_queue.put(j, next_t=0)
j.schedule_removal()
with pytest.raises(ValueError, match='can not be set to'):
j.repeat = True
j.interval = 15
assert j.interval_seconds == 15
j.repeat = True
with pytest.raises(ValueError, match='can not be'):
j.interval = None
j.repeat = False
with pytest.raises(ValueError, match='must be of type'):
j.interval = 'every 3 minutes'
j.interval = 15
assert j.interval_seconds == 15
if __name__ == '__main__': with pytest.raises(ValueError, match='argument should be of type'):
unittest.main() j.days = 'every day'
with pytest.raises(ValueError, match='The elements of the'):
j.days = ('mon', 'wed')
with pytest.raises(ValueError, match='from 0 up to and'):
j.days = (0, 6, 12, 14)

View file

@ -1,76 +1,54 @@
#!/usr/bin/env python #!/usr/bin/env python
# encoding: utf-8
# #
# A library that provides a Python interface to the Telegram Bot API # A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017 # Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
KeyboardButton"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import KeyboardButton
import telegram
from tests.base import BaseTest
class KeyboardButtonTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram KeyboardButton.""" def keyboard_button():
return KeyboardButton(TestKeyboardButton.text,
def setUp(self): request_location=TestKeyboardButton.request_location,
self.text = 'text' request_contact=TestKeyboardButton.request_contact)
self.request_location = True
self.request_contact = True
self.json_dict = {
'text': self.text,
'request_location': self.request_location,
'request_contact': self.request_contact,
}
def test_keyboard_button_de_json(self):
keyboard_button = telegram.KeyboardButton.de_json(self.json_dict, self._bot)
self.assertEqual(keyboard_button.text, self.text)
self.assertEqual(keyboard_button.request_location, self.request_location)
self.assertEqual(keyboard_button.request_contact, self.request_contact)
def test_keyboard_button_de_json_empty(self):
keyboard_button = telegram.KeyboardButton.de_json(None, self._bot)
self.assertFalse(keyboard_button)
def test_keyboard_button_de_list_empty(self):
keyboard_button = telegram.KeyboardButton.de_list(None, self._bot)
self.assertFalse(keyboard_button)
def test_keyboard_button_to_json(self):
keyboard_button = telegram.KeyboardButton.de_json(self.json_dict, self._bot)
self.assertTrue(self.is_json(keyboard_button.to_json()))
def test_keyboard_button_to_dict(self):
keyboard_button = telegram.KeyboardButton.de_json(self.json_dict, self._bot).to_dict()
self.assertTrue(self.is_dict(keyboard_button))
self.assertDictEqual(self.json_dict, keyboard_button)
if __name__ == '__main__': class TestKeyboardButton(object):
unittest.main() text = 'text'
request_location = True
request_contact = True
def test_expected_values(self, keyboard_button):
assert keyboard_button.text == self.text
assert keyboard_button.request_location == self.request_location
assert keyboard_button.request_contact == self.request_contact
def test_de_list(self, bot, keyboard_button):
keyboard_json = [keyboard_button.to_dict(), keyboard_button.to_dict()]
inline_keyboard_buttons = KeyboardButton.de_list(keyboard_json, bot)
assert inline_keyboard_buttons == [keyboard_button, keyboard_button]
def test_to_dict(self, keyboard_button):
keyboard_button_dict = keyboard_button.to_dict()
assert isinstance(keyboard_button_dict, dict)
assert keyboard_button_dict['text'] == keyboard_button.text
assert keyboard_button_dict['request_location'] == keyboard_button.request_location
assert keyboard_button_dict['request_contact'] == keyboard_button.request_contact

View file

@ -5,55 +5,39 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
LabeledPrice"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import LabeledPrice
import telegram
from tests.base import BaseTest
class LabeledPriceTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram LabeledPrice.""" def labeled_price():
return LabeledPrice(TestLabeledPrice.label, TestLabeledPrice.amount)
def setUp(self):
self.label = 'label'
self.amount = 100
self.json_dict = {'label': self.label, 'amount': self.amount}
def test_labeledprice_de_json(self):
labeledprice = telegram.LabeledPrice.de_json(self.json_dict, self._bot)
self.assertEqual(labeledprice.label, self.label)
self.assertEqual(labeledprice.amount, self.amount)
def test_labeledprice_to_json(self):
labeledprice = telegram.LabeledPrice.de_json(self.json_dict, self._bot)
self.assertTrue(self.is_json(labeledprice.to_json()))
def test_labeledprice_to_dict(self):
labeledprice = telegram.LabeledPrice.de_json(self.json_dict, self._bot).to_dict()
self.assertTrue(self.is_dict(labeledprice))
self.assertDictEqual(self.json_dict, labeledprice)
if __name__ == '__main__': class TestLabeledPrice(object):
unittest.main() label = 'label'
amount = 100
def test_expected_values(self, labeled_price):
assert labeled_price.label == self.label
assert labeled_price.amount == self.amount
def test_to_dict(self, labeled_price):
labeled_price_dict = labeled_price.to_dict()
assert isinstance(labeled_price_dict, dict)
assert labeled_price_dict['label'] == labeled_price.label
assert labeled_price_dict['amount'] == labeled_price.amount

View file

@ -5,110 +5,67 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram Location"""
import unittest import pytest
import sys
from flaky import flaky from telegram import Location
sys.path.append('.')
import telegram
from tests.base import BaseTest
class LocationTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram Location.""" def location():
return Location(latitude=TestLocation.latitude, longitude=TestLocation.longitude)
def setUp(self):
self.latitude = -23.691288
self.longitude = -46.788279
self.json_dict = {'latitude': self.latitude, 'longitude': self.longitude} class TestLocation(object):
latitude = -23.691288
longitude = -46.788279
def test_send_location_implicit_args(self): def test_de_json(self, bot):
message = self._bot.sendLocation(self._chat_id, self.latitude, self.longitude) json_dict = {'latitude': TestLocation.latitude,
'longitude': TestLocation.longitude}
location = Location.de_json(json_dict, bot)
location = message.location assert location.latitude == self.latitude
assert location.longitude == self.longitude
self.assertEqual(location.latitude, self.latitude) def test_send_with_location(self, monkeypatch, bot, chat_id, location):
self.assertEqual(location.longitude, self.longitude) def test(_, url, data, **kwargs):
lat = data['latitude'] == location.latitude
lon = data['longitude'] == location.longitude
return lat and lon
def test_send_location_explicit_args(self): monkeypatch.setattr('telegram.utils.request.Request.post', test)
message = self._bot.sendLocation( assert bot.send_location(location=location, chat_id=chat_id)
chat_id=self._chat_id, latitude=self.latitude, longitude=self.longitude)
location = message.location def test_send_location_without_required(self, bot, chat_id):
with pytest.raises(ValueError, match='Either location or latitude and longitude'):
bot.send_location(chat_id=chat_id)
self.assertEqual(location.latitude, self.latitude) def test_to_dict(self, location):
self.assertEqual(location.longitude, self.longitude) location_dict = location.to_dict()
def test_send_location_with_location(self): assert location_dict['latitude'] == location.latitude
loc = telegram.Location(longitude=self.longitude, latitude=self.latitude) assert location_dict['longitude'] == location.longitude
message = self._bot.send_location(location=loc, chat_id=self._chat_id)
location = message.location
self.assertEqual(location, loc)
def test_location_de_json(self):
location = telegram.Location.de_json(self.json_dict, self._bot)
self.assertEqual(location.latitude, self.latitude)
self.assertEqual(location.longitude, self.longitude)
def test_location_to_json(self):
location = telegram.Location.de_json(self.json_dict, self._bot)
self.assertTrue(self.is_json(location.to_json()))
def test_location_to_dict(self):
location = telegram.Location.de_json(self.json_dict, self._bot)
self.assertEqual(location['latitude'], self.latitude)
self.assertEqual(location['longitude'], self.longitude)
def test_error_location_without_required_args(self):
json_dict = self.json_dict
del (json_dict['latitude'])
del (json_dict['longitude'])
with self.assertRaises(ValueError):
self._bot.sendLocation(chat_id=self._chat_id, **json_dict)
@flaky(3, 1)
def test_reply_location(self):
"""Test for Message.reply_location"""
message = self._bot.sendMessage(self._chat_id, '.')
message = message.reply_location(self.latitude, self.longitude)
self.assertEqual(message.location.latitude, self.latitude)
self.assertEqual(message.location.longitude, self.longitude)
def test_equality(self): def test_equality(self):
a = telegram.Location(self.longitude, self.latitude) a = Location(self.longitude, self.latitude)
b = telegram.Location(self.longitude, self.latitude) b = Location(self.longitude, self.latitude)
d = telegram.Location(0, self.latitude) d = Location(0, self.latitude)
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
if __name__ == '__main__':
unittest.main()

View file

@ -1,222 +1,432 @@
#!/usr/bin/env python #!/usr/bin/env python
# encoding: utf-8
# #
# A library that provides a Python interface to the Telegram Bot API # A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017 # Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram Message""" from datetime import datetime
import sys import pytest
import unittest
from flaky import flaky from telegram import (Update, Message, User, MessageEntity, Chat, Audio, Document,
Game, PhotoSize, Sticker, Video, Voice, VideoNote, Contact, Location, Venue,
sys.path.append('.') Invoice, SuccessfulPayment)
import telegram
from tests.base import BaseTest
class MessageTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram MessageTest.""" def message(bot):
return Message(TestMessage.id, TestMessage.from_user, TestMessage.date, TestMessage.chat,
bot=bot)
def setUp(self):
self.test_entities = [
{
'length': 4,
'offset': 10,
'type': 'bold'
},
{
'length': 7,
'offset': 16,
'type': 'italic'
},
{
'length': 4,
'offset': 25,
'type': 'code'
},
{
'length': 5,
'offset': 31,
'type': 'text_link',
'url': 'http://github.com/'
},
{
'length': 3,
'offset': 41,
'type': 'pre'
},
]
self.test_text = 'Test for <bold, ita_lic, code, links and pre.' @pytest.fixture(scope='function',
self.test_message = telegram.Message( params=[
message_id=1, {'forward_from': User(99, 'forward_user'),
'forward_date': datetime.now()},
{'forward_from_chat': Chat(-23, 'channel'),
'forward_from_message_id': 101,
'forward_date': datetime.now()},
{'reply_to_message': Message(50, None, None, None)},
{'edit_date': datetime.now()},
{'test': 'a text message',
'enitites': [MessageEntity('bold', 10, 4),
MessageEntity('italic', 16, 7)]},
{'audio': Audio('audio_id', 12),
'caption': 'audio_file'},
{'document': Document('document_id'),
'caption': 'document_file'},
{'game': Game('my_game', 'just my game',
[PhotoSize('game_photo_id', 30, 30), ])},
{'photo': [PhotoSize('photo_id', 50, 50)],
'caption': 'photo_file'},
{'sticker': Sticker('sticker_id', 50, 50)},
{'video': Video('video_id', 12, 12, 12),
'caption': 'video_file'},
{'voice': Voice('voice_id', 5)},
{'video_note': VideoNote('video_note_id', 20, 12)},
{'new_chat_members': [User(55, 'new_user')]},
{'contact': Contact('phone_numner', 'contact_name')},
{'location': Location(-23.691288, 46.788279)},
{'venue': Venue(Location(-23.691288, 46.788279),
'some place', 'right here')},
{'left_chat_member': User(33, 'kicked')},
{'new_chat_title': 'new title'},
{'new_chat_photo': [PhotoSize('photo_id', 50, 50)]},
{'delete_chat_photo': True},
{'group_chat_created': True},
{'supergroup_chat_created': True},
{'channel_chat_created': True},
{'migrate_to_chat_id': -12345},
{'migrate_from_chat_id': -54321},
{'pinned_message': Message(7, None, None, None)},
{'invoice': Invoice('my invoice', 'invoice', 'start', 'EUR', 243)},
{'successful_payment': SuccessfulPayment('EUR', 243, 'payload',
'charge_id', 'provider_id',
order_info={})}
],
ids=['forwarded_user', 'forwarded_channel', 'reply', 'edited', 'text', 'audio',
'document', 'game', 'photo', 'sticker', 'video', 'voice', 'video_note',
'new_members', 'contact', 'location', 'venue', 'left_member', 'new_title',
'new_photo', 'delete_photo', 'group_created', 'supergroup_created',
'channel_created', 'migrated_to', 'migrated_from', 'pinned', 'invoice',
'successful_payment'])
def message_params(bot, request):
return Message(message_id=TestMessage.id,
from_user=TestMessage.from_user,
date=TestMessage.date,
chat=TestMessage.chat, bot=bot, **request.param)
class TestMessage(object):
id = 1
from_user = User(2, 'testuser')
date = datetime.now()
chat = Chat(3, 'private')
test_entities = [{'length': 4, 'offset': 10, 'type': 'bold'},
{'length': 7, 'offset': 16, 'type': 'italic'},
{'length': 4, 'offset': 25, 'type': 'code'},
{'length': 5, 'offset': 31, 'type': 'text_link', 'url': 'http://github.com/'},
{'length': 3, 'offset': 41, 'type': 'pre'},
{'length': 17, 'offset': 46, 'type': 'url'}]
test_text = 'Test for <bold, ita_lic, code, links and pre. http://google.com'
test_message = Message(message_id=1,
from_user=None, from_user=None,
date=None, date=None,
chat=None, chat=None,
text=self.test_text, text=test_text,
entities=[telegram.MessageEntity(**e) for e in self.test_entities]) entities=[MessageEntity(**e) for e in test_entities])
def test_all_posibilities_de_json_and_to_dict(self, bot, message_params):
new = Message.de_json(message_params.to_dict(), bot)
assert new.to_dict() == message_params.to_dict()
def test_dict_approach(self, message):
assert message['date'] == message.date
assert message['chat_id'] == message.chat_id
assert message['no_key'] is None
def test_parse_entity(self): def test_parse_entity(self):
text = (b'\\U0001f469\\u200d\\U0001f469\\u200d\\U0001f467' text = (b'\\U0001f469\\u200d\\U0001f469\\u200d\\U0001f467'
b'\\u200d\\U0001f467\\U0001f431http://google.com').decode('unicode-escape') b'\\u200d\\U0001f467\\U0001f431http://google.com').decode('unicode-escape')
entity = telegram.MessageEntity(type=telegram.MessageEntity.URL, offset=13, length=17) entity = MessageEntity(type=MessageEntity.URL, offset=13, length=17)
message = telegram.Message( message = Message(1, self.from_user, self.date, self.chat, text=text, entities=[entity])
message_id=1, from_user=None, date=None, chat=None, text=text, entities=[entity]) assert message.parse_entity(entity) == 'http://google.com'
self.assertEqual(message.parse_entity(entity), 'http://google.com')
def test_parse_entities(self): def test_parse_entities(self):
text = (b'\\U0001f469\\u200d\\U0001f469\\u200d\\U0001f467' text = (b'\\U0001f469\\u200d\\U0001f469\\u200d\\U0001f467'
b'\\u200d\\U0001f467\\U0001f431http://google.com').decode('unicode-escape') b'\\u200d\\U0001f467\\U0001f431http://google.com').decode('unicode-escape')
entity = telegram.MessageEntity(type=telegram.MessageEntity.URL, offset=13, length=17) entity = MessageEntity(type=MessageEntity.URL, offset=13, length=17)
entity_2 = telegram.MessageEntity(type=telegram.MessageEntity.BOLD, offset=13, length=1) entity_2 = MessageEntity(type=MessageEntity.BOLD, offset=13, length=1)
message = telegram.Message( message = Message(1, self.from_user, self.date, self.chat,
message_id=1, text=text, entities=[entity_2, entity])
from_user=None, assert message.parse_entities(MessageEntity.URL) == {entity: 'http://google.com'}
date=None, assert message.parse_entities() == {entity: 'http://google.com', entity_2: 'h'}
chat=None,
text=text,
entities=[entity_2, entity])
self.assertDictEqual(
message.parse_entities(telegram.MessageEntity.URL), {entity: 'http://google.com'})
self.assertDictEqual(message.parse_entities(),
{entity: 'http://google.com',
entity_2: 'h'})
def test_text_html_simple(self): def test_text_html_simple(self):
test_html_string = 'Test for &lt;<b>bold</b>, <i>ita_lic</i>, <code>code</code>, <a href="http://github.com/">links</a> and <pre>pre</pre>.' test_html_string = ('Test for &lt;<b>bold</b>, <i>ita_lic</i>, <code>code</code>, '
'<a href="http://github.com/">links</a> and <pre>pre</pre>. '
'http://google.com')
text_html = self.test_message.text_html text_html = self.test_message.text_html
self.assertEquals(test_html_string, text_html) assert text_html == test_html_string
def test_text_html_urled(self):
test_html_string = ('Test for &lt;<b>bold</b>, <i>ita_lic</i>, <code>code</code>, '
'<a href="http://github.com/">links</a> and <pre>pre</pre>. '
'<a href="http://google.com">http://google.com</a>')
text_html = self.test_message.text_html_urled
assert text_html == test_html_string
def test_text_markdown_simple(self): def test_text_markdown_simple(self):
test_md_string = 'Test for <*bold*, _ita\_lic_, `code`, [links](http://github.com/) and ```pre```.' test_md_string = ('Test for <*bold*, _ita\_lic_, `code`, [links](http://github.com/) and '
'```pre```. http://google.com')
text_markdown = self.test_message.text_markdown text_markdown = self.test_message.text_markdown
self.assertEquals(test_md_string, text_markdown) assert text_markdown == test_md_string
def test_text_markdown_urled(self):
test_md_string = ('Test for <*bold*, _ita\_lic_, `code`, [links](http://github.com/) and '
'```pre```. [http://google.com](http://google.com)')
text_markdown = self.test_message.text_markdown_urled
assert text_markdown == test_md_string
def test_text_html_emoji(self): def test_text_html_emoji(self):
text = (b'\\U0001f469\\u200d\\U0001f469\\u200d ABC').decode('unicode-escape') text = b'\\U0001f469\\u200d\\U0001f469\\u200d ABC'.decode('unicode-escape')
expected = (b'\\U0001f469\\u200d\\U0001f469\\u200d <b>ABC</b>').decode('unicode-escape') expected = b'\\U0001f469\\u200d\\U0001f469\\u200d <b>ABC</b>'.decode('unicode-escape')
bold_entity = telegram.MessageEntity(type=telegram.MessageEntity.BOLD, offset=7, length=3) bold_entity = MessageEntity(type=MessageEntity.BOLD, offset=7, length=3)
message = telegram.Message( message = Message(1, self.from_user, self.date, self.chat,
message_id=1, from_user=None, date=None, chat=None, text=text, entities=[bold_entity]) text=text, entities=[bold_entity])
self.assertEquals(expected, message.text_html) assert expected == message.text_html
def test_text_markdown_emoji(self): def test_text_markdown_emoji(self):
text = (b'\\U0001f469\\u200d\\U0001f469\\u200d ABC').decode('unicode-escape') text = b'\\U0001f469\\u200d\\U0001f469\\u200d ABC'.decode('unicode-escape')
expected = (b'\\U0001f469\\u200d\\U0001f469\\u200d *ABC*').decode('unicode-escape') expected = b'\\U0001f469\\u200d\\U0001f469\\u200d *ABC*'.decode('unicode-escape')
bold_entity = telegram.MessageEntity(type=telegram.MessageEntity.BOLD, offset=7, length=3) bold_entity = MessageEntity(type=MessageEntity.BOLD, offset=7, length=3)
message = telegram.Message( message = Message(1, self.from_user, self.date, self.chat,
message_id=1, from_user=None, date=None, chat=None, text=text, entities=[bold_entity]) text=text, entities=[bold_entity])
self.assertEquals(expected, message.text_markdown) assert expected == message.text_markdown
def test_parse_entities_url_emoji(self): def test_parse_entities_url_emoji(self):
url = b'http://github.com/?unicode=\\u2713\\U0001f469'.decode('unicode-escape') url = b'http://github.com/?unicode=\\u2713\\U0001f469'.decode('unicode-escape')
text = 'some url' text = 'some url'
link_entity = telegram.MessageEntity(type=telegram.MessageEntity.URL, offset=0, length=8, url=url) link_entity = MessageEntity(type=MessageEntity.URL, offset=0, length=8, url=url)
message = telegram.Message( message = Message(1, self.from_user, self.date, self.chat,
message_id=1, text=text, entities=[link_entity])
from_user=None, assert message.parse_entities() == {link_entity: text}
date=None, assert next(iter(message.parse_entities())).url == url
chat=None,
text=text,
entities=[link_entity])
self.assertDictEqual(message.parse_entities(), {link_entity: text})
self.assertEqual(next(iter(message.parse_entities())).url, url)
@flaky(3, 1) def test_chat_id(self, message):
def test_reply_text(self): assert message.chat_id == message.chat.id
"""Test for Message.reply_text"""
message = self._bot.sendMessage(self._chat_id, '.')
message = message.reply_text('Testing class method')
self.assertTrue(self.is_json(message.to_json())) def test_effective_attachment(self, message_params):
self.assertEqual(message.text, 'Testing class method')
@flaky(3, 1)
def test_forward(self):
"""Test for Message.forward"""
message = self._bot.sendMessage(self._chat_id, 'Testing class method')
message = message.forward(self._chat_id)
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(message.text, 'Testing class method')
@flaky(3, 1)
def test_edit_text(self):
"""Test for Message.edit_text"""
message = self._bot.sendMessage(self._chat_id, '.')
message = message.edit_text('Testing class method')
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(message.text, 'Testing class method')
@flaky(3, 1)
def test_delete1(self):
"""Test for Message.delete"""
message = self._bot.send_message(
chat_id=self._chat_id, text='This message will be deleted')
self.assertTrue(message.delete())
@flaky(3, 1)
def test_delete2(self):
"""Another test for Message.delete"""
message = self._bot.send_message(
chat_id=self._chat_id,
text='This ^ message will not be deleted',
reply_to_message_id=1)
with self.assertRaisesRegexp(telegram.TelegramError, "can't be deleted"):
message.reply_to_message.delete()
def test_equality(self):
_id = 1
a = telegram.Message(_id, telegram.User(1, ""), None, None)
b = telegram.Message(_id, telegram.User(1, ""), None, None)
c = telegram.Message(_id, telegram.User(0, ""), None, None)
d = telegram.Message(0, telegram.User(1, ""), None, None)
e = telegram.Update(_id)
self.assertEqual(a, b)
self.assertEqual(hash(a), hash(b))
self.assertIsNot(a, b)
self.assertEqual(a, c)
self.assertEqual(hash(a), hash(c))
self.assertNotEqual(a, d)
self.assertNotEqual(hash(a), hash(d))
self.assertNotEqual(a, e)
self.assertNotEqual(hash(a), hash(e))
def test_effective_attachment(self):
for i in ('audio', 'game', 'document', 'photo', 'sticker', 'video', 'voice', 'video_note', for i in ('audio', 'game', 'document', 'photo', 'sticker', 'video', 'voice', 'video_note',
'contact', 'location', 'venue', 'invoice', 'invoice', 'successful_payment'): 'contact', 'location', 'venue', 'invoice', 'invoice', 'successful_payment'):
dummy = object() item = getattr(message_params, i, None)
kwargs = {i: dummy} if item:
msg = telegram.Message(1, telegram.User(1, ""), None, None, **kwargs) break
self.assertIs(msg.effective_attachment, dummy, else:
'invalid {} effective attachment'.format(i)) item = None
assert message_params.effective_attachment == item
msg = telegram.Message(1, telegram.User(1, ""), None, None)
self.assertIsNone(msg.effective_attachment)
if __name__ == '__main__': def test_reply_text(self, monkeypatch, message):
unittest.main() def test(*args, **kwargs):
id = args[1] == message.chat_id
text = args[2] == 'test'
if kwargs.get('reply_to_message_id'):
reply = kwargs['reply_to_message_id'] == message.message_id
else:
reply = True
return id and text and reply
monkeypatch.setattr('telegram.Bot.send_message', test)
assert message.reply_text('test')
assert message.reply_text('test', quote=True)
assert message.reply_text('test', reply_to_message_id=message.message_id, quote=True)
def test_reply_photo(self, monkeypatch, message):
def test(*args, **kwargs):
id = args[1] == message.chat_id
photo = kwargs['photo'] == 'test_photo'
if kwargs.get('reply_to_message_id'):
reply = kwargs['reply_to_message_id'] == message.message_id
else:
reply = True
return id and photo and reply
monkeypatch.setattr('telegram.Bot.send_photo', test)
assert message.reply_photo(photo='test_photo')
assert message.reply_photo(photo='test_photo', quote=True)
def test_reply_audio(self, monkeypatch, message):
def test(*args, **kwargs):
id = args[1] == message.chat_id
audio = kwargs['audio'] == 'test_audio'
if kwargs.get('reply_to_message_id'):
reply = kwargs['reply_to_message_id'] == message.message_id
else:
reply = True
return id and audio and reply
monkeypatch.setattr('telegram.Bot.send_audio', test)
assert message.reply_audio(audio='test_audio')
assert message.reply_audio(audio='test_audio', quote=True)
def test_reply_document(self, monkeypatch, message):
def test(*args, **kwargs):
id = args[1] == message.chat_id
document = kwargs['document'] == 'test_document'
if kwargs.get('reply_to_message_id'):
reply = kwargs['reply_to_message_id'] == message.message_id
else:
reply = True
return id and document and reply
monkeypatch.setattr('telegram.Bot.send_document', test)
assert message.reply_document(document='test_document')
assert message.reply_document(document='test_document', quote=True)
def test_reply_sticker(self, monkeypatch, message):
def test(*args, **kwargs):
id = args[1] == message.chat_id
sticker = kwargs['sticker'] == 'test_sticker'
if kwargs.get('reply_to_message_id'):
reply = kwargs['reply_to_message_id'] == message.message_id
else:
reply = True
return id and sticker and reply
monkeypatch.setattr('telegram.Bot.send_sticker', test)
assert message.reply_sticker(sticker='test_sticker')
assert message.reply_sticker(sticker='test_sticker', quote=True)
def test_reply_video(self, monkeypatch, message):
def test(*args, **kwargs):
id = args[1] == message.chat_id
video = kwargs['video'] == 'test_video'
if kwargs.get('reply_to_message_id'):
reply = kwargs['reply_to_message_id'] == message.message_id
else:
reply = True
return id and video and reply
monkeypatch.setattr('telegram.Bot.send_video', test)
assert message.reply_video(video='test_video')
assert message.reply_video(video='test_video', quote=True)
def test_reply_video_note(self, monkeypatch, message):
def test(*args, **kwargs):
id = args[1] == message.chat_id
video_note = kwargs['video_note'] == 'test_video_note'
if kwargs.get('reply_to_message_id'):
reply = kwargs['reply_to_message_id'] == message.message_id
else:
reply = True
return id and video_note and reply
monkeypatch.setattr('telegram.Bot.send_video_note', test)
assert message.reply_video_note(video_note='test_video_note')
assert message.reply_video_note(video_note='test_video_note', quote=True)
def test_reply_voice(self, monkeypatch, message):
def test(*args, **kwargs):
id = args[1] == message.chat_id
voice = kwargs['voice'] == 'test_voice'
if kwargs.get('reply_to_message_id'):
reply = kwargs['reply_to_message_id'] == message.message_id
else:
reply = True
return id and voice and reply
monkeypatch.setattr('telegram.Bot.send_voice', test)
assert message.reply_voice(voice='test_voice')
assert message.reply_voice(voice='test_voice', quote=True)
def test_reply_location(self, monkeypatch, message):
def test(*args, **kwargs):
id = args[1] == message.chat_id
location = kwargs['location'] == 'test_location'
if kwargs.get('reply_to_message_id'):
reply = kwargs['reply_to_message_id'] == message.message_id
else:
reply = True
return id and location and reply
monkeypatch.setattr('telegram.Bot.send_location', test)
assert message.reply_location(location='test_location')
assert message.reply_location(location='test_location', quote=True)
def test_reply_venue(self, monkeypatch, message):
def test(*args, **kwargs):
id = args[1] == message.chat_id
venue = kwargs['venue'] == 'test_venue'
if kwargs.get('reply_to_message_id'):
reply = kwargs['reply_to_message_id'] == message.message_id
else:
reply = True
return id and venue and reply
monkeypatch.setattr('telegram.Bot.send_venue', test)
assert message.reply_venue(venue='test_venue')
assert message.reply_venue(venue='test_venue', quote=True)
def test_reply_contact(self, monkeypatch, message):
def test(*args, **kwargs):
id = args[1] == message.chat_id
contact = kwargs['contact'] == 'test_contact'
if kwargs.get('reply_to_message_id'):
reply = kwargs['reply_to_message_id'] == message.message_id
else:
reply = True
return id and contact and reply
monkeypatch.setattr('telegram.Bot.send_contact', test)
assert message.reply_contact(contact='test_contact')
assert message.reply_contact(contact='test_contact', quote=True)
def test_forward(self, monkeypatch, message):
def test(*args, **kwargs):
chat_id = kwargs['chat_id'] == 123456
from_chat = kwargs['from_chat_id'] == message.chat_id
message_id = kwargs['message_id'] == message.message_id
if kwargs.get('disable_notification'):
notification = kwargs['disable_notification'] is True
else:
notification = True
return chat_id and from_chat and message_id and notification
monkeypatch.setattr('telegram.Bot.forward_message', test)
assert message.forward(123456)
assert message.forward(123456, disable_notification=True)
assert not message.forward(635241)
def test_edit_text(self, monkeypatch, message):
def test(*args, **kwargs):
chat_id = kwargs['chat_id'] == message.chat_id
message_id = kwargs['message_id'] == message.message_id
text = kwargs['text'] == 'test'
return chat_id and message_id and text
monkeypatch.setattr('telegram.Bot.edit_message_text', test)
assert message.edit_text(text='test')
def test_edit_caption(self, monkeypatch, message):
def test(*args, **kwargs):
chat_id = kwargs['chat_id'] == message.chat_id
message_id = kwargs['message_id'] == message.message_id
caption = kwargs['caption'] == 'new caption'
return chat_id and message_id and caption
monkeypatch.setattr('telegram.Bot.edit_message_caption', test)
assert message.edit_caption(caption='new caption')
def test_edit_reply_markup(self, monkeypatch, message):
def test(*args, **kwargs):
chat_id = kwargs['chat_id'] == message.chat_id
message_id = kwargs['message_id'] == message.message_id
reply_markup = kwargs['reply_markup'] == [['1', '2']]
return chat_id and message_id and reply_markup
monkeypatch.setattr('telegram.Bot.edit_message_reply_markup', test)
assert message.edit_reply_markup(reply_markup=[['1', '2']])
def test_delete(self, monkeypatch, message):
def test(*args, **kwargs):
chat_id = kwargs['chat_id'] == message.chat_id
message_id = kwargs['message_id'] == message.message_id
return chat_id and message_id
monkeypatch.setattr('telegram.Bot.delete_message', test)
assert message.delete()
def test_equality(self):
id = 1
a = Message(id, self.from_user, self.date, self.chat)
b = Message(id, self.from_user, self.date, self.chat)
c = Message(id, User(0, ''), self.date, self.chat)
d = Message(0, self.from_user, self.date, self.chat)
e = Update(id)
assert a == b
assert hash(a) == hash(b)
assert a is not b
assert a == c
assert hash(a) == hash(c)
assert a != d
assert hash(a) != hash(d)
assert a != e
assert hash(a) != hash(e)

View file

@ -5,64 +5,62 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
MessageEntity"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import MessageEntity, User
import telegram
from tests.base import BaseTest
class MessageEntityTest(BaseTest, unittest.TestCase): @pytest.fixture(scope="class",
"""This object represents Tests for Telegram MessageEntity.""" params=MessageEntity.ALL_TYPES)
def message_entity(request):
type = request.param
url = None
if type == MessageEntity.TEXT_LINK:
url = 't.me'
user = None
if type == MessageEntity.TEXT_MENTION:
user = User(1, 'test_user')
return MessageEntity(type, 1, 3, url=url, user=user)
def setUp(self):
self.type = 'type'
self.offset = 1
self.length = 2
self.url = 'url'
self.json_dict = { class TestMessageEntity(object):
type = 'url'
offset = 1
length = 2
url = 'url'
def test_de_json(self, bot):
json_dict = {
'type': self.type, 'type': self.type,
'offset': self.offset, 'offset': self.offset,
'length': self.length, 'length': self.length
'url': self.url
} }
entity = MessageEntity.de_json(json_dict, bot)
def test_messageentity_de_json(self): assert entity.type == self.type
entity = telegram.MessageEntity.de_json(self.json_dict, self._bot) assert entity.offset == self.offset
assert entity.length == self.length
self.assertEqual(entity.type, self.type) def test_to_dict(self, message_entity):
self.assertEqual(entity.offset, self.offset) entity_dict = message_entity.to_dict()
self.assertEqual(entity.length, self.length)
self.assertEqual(entity.url, self.url)
def test_messageentity_to_json(self): assert isinstance(entity_dict, dict)
entity = telegram.MessageEntity.de_json(self.json_dict, self._bot) assert entity_dict['type'] == message_entity.type
assert entity_dict['offset'] == message_entity.offset
self.assertTrue(self.is_json(entity.to_json())) assert entity_dict['length'] == message_entity.length
if message_entity.url:
def test_messageentity_to_dict(self): assert entity_dict['url'] == message_entity.url
entity = telegram.MessageEntity.de_json(self.json_dict, self._bot).to_dict() if message_entity.user:
assert entity_dict['user'] == message_entity.user.to_dict()
self.assertTrue(self.is_dict(entity))
self.assertDictEqual(self.json_dict, entity)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,184 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
import pytest
from telegram import (Message, Update, Chat, Bot, User, CallbackQuery, InlineQuery,
ChosenInlineResult, ShippingQuery, PreCheckoutQuery)
from telegram.ext import Filters, MessageHandler
message = Message(1, User(1, ''), None, Chat(1, ''), text='Text')
params = [
{'callback_query': CallbackQuery(1, User(1, ''), 'chat', message=message)},
{'inline_query': InlineQuery(1, User(1, ''), '', '')},
{'chosen_inline_result': ChosenInlineResult('id', User(1, ''), '')},
{'shipping_query': ShippingQuery('id', User(1, ''), '', None)},
{'pre_checkout_query': PreCheckoutQuery('id', User(1, ''), '', 0, '')},
{'callback_query': CallbackQuery(1, User(1, ''), 'chat')}
]
ids = ('callback_query', 'inline_query', 'chosen_inline_result',
'shipping_query', 'pre_checkout_query', 'callback_query_without_message')
@pytest.fixture(scope='class', params=params, ids=ids)
def false_update(request):
return Update(update_id=1, **request.param)
@pytest.fixture(scope='class')
def message(bot):
return Message(1, None, None, None, bot=bot)
class TestMessageHandler(object):
test_flag = False
@pytest.fixture(autouse=True)
def reset(self):
self.test_flag = False
def callback_basic(self, bot, update):
test_bot = isinstance(bot, Bot)
test_update = isinstance(update, Update)
self.test_flag = test_bot and test_update
def callback_data_1(self, bot, update, user_data=None, chat_data=None):
self.test_flag = (user_data is not None) or (chat_data is not None)
def callback_data_2(self, bot, update, user_data=None, chat_data=None):
self.test_flag = (user_data is not None) and (chat_data is not None)
def callback_queue_1(self, bot, update, job_queue=None, update_queue=None):
self.test_flag = (job_queue is not None) or (update_queue is not None)
def callback_queue_2(self, bot, update, job_queue=None, update_queue=None):
self.test_flag = (job_queue is not None) and (update_queue is not None)
def test_basic(self, dp, message):
handler = MessageHandler(None, self.callback_basic)
dp.add_handler(handler)
assert handler.check_update(Update(0, message))
dp.process_update(Update(0, message))
assert self.test_flag
def test_edited(self, message):
handler = MessageHandler(None, self.callback_basic, edited_updates=True,
message_updates=False, channel_post_updates=False)
assert handler.check_update(Update(0, edited_message=message))
assert not handler.check_update(Update(0, message=message))
assert not handler.check_update(Update(0, channel_post=message))
assert not handler.check_update(Update(0, edited_channel_post=message))
def test_channel_post(self, message):
handler = MessageHandler(None, self.callback_basic, edited_updates=False,
message_updates=False, channel_post_updates=True)
assert not handler.check_update(Update(0, edited_message=message))
assert not handler.check_update(Update(0, message=message))
assert handler.check_update(Update(0, channel_post=message))
assert not handler.check_update(Update(0, edited_channel_post=message))
def test_multiple_flags(self, message):
handler = MessageHandler(None, self.callback_basic, edited_updates=True,
message_updates=True, channel_post_updates=True)
assert handler.check_update(Update(0, edited_message=message))
assert handler.check_update(Update(0, message=message))
assert handler.check_update(Update(0, channel_post=message))
assert not handler.check_update(Update(0, edited_channel_post=message))
def test_allow_updated(self, message):
with pytest.warns(UserWarning):
handler = MessageHandler(None, self.callback_basic, message_updates=True,
allow_edited=True)
assert handler.check_update(Update(0, edited_message=message))
assert handler.check_update(Update(0, message=message))
assert handler.check_update(Update(0, channel_post=message))
assert not handler.check_update(Update(0, edited_channel_post=message))
def test_none_allowed(self):
with pytest.raises(ValueError, match='are all False'):
handler = MessageHandler(None, self.callback_basic, message_updates=False,
channel_post_updates=False, edited_updates=False)
def test_with_filter(self, message):
handler = MessageHandler(Filters.command, self.callback_basic)
message.text = '/test'
assert handler.check_update(Update(0, message))
message.text = 'test'
assert not handler.check_update(Update(0, message))
def test_pass_user_or_chat_data(self, dp, message):
handler = MessageHandler(None, self.callback_data_1, pass_user_data=True)
dp.add_handler(handler)
dp.process_update(Update(0, message=message))
assert self.test_flag
dp.remove_handler(handler)
handler = MessageHandler(None, self.callback_data_1, pass_chat_data=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(Update(0, message=message))
assert self.test_flag
dp.remove_handler(handler)
handler = MessageHandler(None, self.callback_data_2, pass_chat_data=True,
pass_user_data=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(Update(0, message=message))
assert self.test_flag
def test_pass_job_or_update_queue(self, dp, message):
handler = MessageHandler(None, self.callback_queue_1, pass_job_queue=True)
dp.add_handler(handler)
dp.process_update(Update(0, message=message))
assert self.test_flag
dp.remove_handler(handler)
handler = MessageHandler(None, self.callback_queue_1, pass_update_queue=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(Update(0, message=message))
assert self.test_flag
dp.remove_handler(handler)
handler = MessageHandler(None, self.callback_queue_2, pass_job_queue=True,
pass_update_queue=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(Update(0, message=message))
assert self.test_flag
def test_other_update_types(self, false_update):
handler = MessageHandler(None, self.callback_basic, edited_updates=True)
assert not handler.check_update(false_update)

View file

@ -1,91 +1,63 @@
'''This module contains telegram.ext.messagequeue test logic''' #!/usr/bin/env python
from __future__ import print_function, division #
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
import sys from time import sleep
import os
import time
import unittest
sys.path.insert(0, os.path.dirname(__file__) + os.sep + '..') import telegram.ext.messagequeue as mq
from tests.base import BaseTest
from telegram.ext import messagequeue as mq
class DelayQueueTest(BaseTest, unittest.TestCase): class TestDelayQueue(object):
N = 128
burst_limit = 30
time_limit_ms = 1000
margin_ms = 0
testtimes = []
def __init__(self, *args, **kwargs): def call(self):
self._N = kwargs.pop('N', 128)
self._msglimit = kwargs.pop('burst_limit', 30)
self._timelimit = kwargs.pop('time_limit_ms', 1000)
self._margin = kwargs.pop('margin_ms', 0)
isprint = kwargs.pop('isprint', False)
def noprint(*args, **kwargs):
pass
self._print = print if isprint else noprint
super(DelayQueueTest, self).__init__(*args, **kwargs)
def setUp(self):
print = self._print
print('Self-test with N = {} msgs, burst_limit = {} msgs, '
'time_limit = {:.2f} ms, margin = {:.2f} ms'
''.format(self._N, self._msglimit, self._timelimit, self._margin))
self.testtimes = []
def testcall():
self.testtimes.append(mq.curtime()) self.testtimes.append(mq.curtime())
self.testcall = testcall
def test_delayqueue_limits(self): def test_delayqueue_limits(self):
'''Test that DelayQueue dispatched calls don't hit time-window limit''' dsp = mq.DelayQueue(burst_limit=self.burst_limit, time_limit_ms=self.time_limit_ms,
print = self._print autostart=True)
dsp = mq.DelayQueue( assert dsp.is_alive() is True
burst_limit=self._msglimit, time_limit_ms=self._timelimit, autostart=True)
print('Started dispatcher {}\nStatus: {}'
''.format(dsp, ['inactive', 'active'][dsp.is_alive()]))
self.assertTrue(dsp.is_alive())
print('Dispatching {} calls @ {}'.format(self._N, time.asctime())) for i in range(self.N):
dsp(self.call)
for i in range(self._N):
dsp(self.testcall)
print('Queue filled, waiting 4 dispatch finish @ ' + str(time.asctime()))
starttime = mq.curtime() starttime = mq.curtime()
app_endtime = ( app_endtime = (
(self._N * self._msglimit / (self.N * self.burst_limit /
(1000 * self._timelimit)) + starttime + 20) # wait up to 20 sec more than needed (1000 * self.time_limit_ms)) + starttime + 20) # wait up to 20 sec more than needed
while not dsp._queue.empty() and mq.curtime() < app_endtime: while not dsp._queue.empty() and mq.curtime() < app_endtime:
time.sleep(1) sleep(1)
self.assertTrue(dsp._queue.empty()) # check loop exit condition assert dsp._queue.empty() is True # check loop exit condition
dsp.stop() dsp.stop()
print('Dispatcher ' + ['stopped', '!NOT STOPPED!'][dsp.is_alive()] + ' @ ' + str( assert dsp.is_alive() is False
time.asctime()))
self.assertFalse(dsp.is_alive())
self.assertTrue(self.testtimes or self._N == 0) assert self.testtimes or self.N == 0 is True
print('Calculating call time windows')
passes, fails = [], [] passes, fails = [], []
delta = (self._timelimit - self._margin) / 1000 delta = (self.time_limit_ms - self.margin_ms) / 1000
it = enumerate(range(self._msglimit + 1, len(self.testtimes))) for start, stop in enumerate(range(self.burst_limit + 1, len(self.testtimes))):
for start, stop in it:
part = self.testtimes[start:stop] part = self.testtimes[start:stop]
if (part[-1] - part[0]) >= delta: if (part[-1] - part[0]) >= delta:
passes.append(part) passes.append(part)
else: else:
fails.append(part) fails.append(part)
assert fails == []
print('Tested: {}, Passed: {}, Failed: {}'
''.format(len(passes + fails), len(passes), len(fails)))
if fails:
print('(!) Got mismatches: ' + ';\n'.join(map(str, fails)))
self.assertFalse(fails)
if __name__ == '__main__':
unittest.main()

42
tests/test_meta.py Normal file
View file

@ -0,0 +1,42 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
import os
import subprocess
import sys
from platform import python_implementation
import pytest
def call_pre_commit_hook(hook_id):
__tracebackhide__ = True
return subprocess.call(['pre-commit', 'run', '--all-files', hook_id])
@pytest.mark.parametrize('hook_id', argvalues=('yapf', 'flake8', 'pylint'))
@pytest.mark.skipif(not os.getenv('TRAVIS'), reason='Not running in travis.')
@pytest.mark.skipif(not sys.version_info[:2] == (3, 6) or python_implementation() != 'CPython',
reason='Only running pre-commit-hooks on newest tested python version, '
'as they are slow and consistent across platforms.')
def test_pre_commit_hook(hook_id):
assert call_pre_commit_hook(hook_id) == 0
def test_build():
assert subprocess.call(['python', 'setup.py', 'bdist_dumb']) == 0

View file

@ -1,11 +1,28 @@
import sys #!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
import inspect import inspect
import warnings import sys
from collections import namedtuple from collections import namedtuple
import platform from platform import python_implementation
import certifi import certifi
import logging import pytest
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
sys.path.append('.') sys.path.append('.')
@ -16,8 +33,6 @@ import telegram
IGNORED_OBJECTS = ('ResponseParameters', 'CallbackGame') IGNORED_OBJECTS = ('ResponseParameters', 'CallbackGame')
IGNORED_PARAMETERS = {'self', 'args', 'kwargs', 'read_latency', 'network_delay', 'timeout', 'bot'} IGNORED_PARAMETERS = {'self', 'args', 'kwargs', 'read_latency', 'network_delay', 'timeout', 'bot'}
logger = logging.getLogger(__name__)
def find_next_sibling_until(tag, name, until): def find_next_sibling_until(tag, name, until):
for sibling in tag.next_siblings: for sibling in tag.next_siblings:
@ -50,7 +65,6 @@ def check_method(h4):
checked = [] checked = []
for parameter in table: for parameter in table:
param = sig.parameters.get(parameter.Parameters) param = sig.parameters.get(parameter.Parameters)
logger.debug(parameter)
assert param is not None assert param is not None
# TODO: Check type via docstring # TODO: Check type via docstring
# TODO: Check if optional or required # TODO: Check if optional or required
@ -70,8 +84,6 @@ def check_method(h4):
elif name == 'sendVenue': elif name == 'sendVenue':
ignored |= {'venue'} # Added for ease of use ignored |= {'venue'} # Added for ease of use
logger.debug((sig.parameters.keys(), checked, ignored,
sig.parameters.keys() - checked - ignored))
assert (sig.parameters.keys() ^ checked) - ignored == set() assert (sig.parameters.keys() ^ checked) - ignored == set()
@ -94,7 +106,6 @@ def check_object(h4):
continue continue
param = sig.parameters.get(field) param = sig.parameters.get(field)
logger.debug(parameter)
assert param is not None assert param is not None
# TODO: Check type via docstring # TODO: Check type via docstring
# TODO: Check if optional or required # TODO: Check if optional or required
@ -111,17 +122,11 @@ def check_object(h4):
if name.startswith('InlineQueryResult'): if name.startswith('InlineQueryResult'):
ignored |= {'type'} ignored |= {'type'}
logger.debug((sig.parameters.keys(), checked, ignored,
sig.parameters.keys() - checked - ignored))
assert (sig.parameters.keys() ^ checked) - ignored == set() assert (sig.parameters.keys() ^ checked) - ignored == set()
def test_official(): argvalues = []
if not sys.version_info >= (3, 5) or platform.python_implementation() != 'CPython': names = []
warnings.warn('Not running "official" tests, since follow_wrapped is not supported'
'on this platform (cpython version >= 3.5 required)')
return
http = urllib3.PoolManager( http = urllib3.PoolManager(
cert_reqs='CERT_REQUIRED', cert_reqs='CERT_REQUIRED',
ca_certs=certifi.where()) ca_certs=certifi.where())
@ -133,28 +138,18 @@ def test_official():
# TODO: don't depend on that # TODO: don't depend on that
if '-' not in thing['name']: if '-' not in thing['name']:
h4 = thing.parent h4 = thing.parent
name = h4.text
test = None
# Is it a method # Is it a method
if h4.text[0].lower() == h4.text[0]: if h4.text[0].lower() == h4.text[0]:
test = check_method argvalues.append((check_method, h4))
else: # Or a type/object names.append(h4.text)
if name not in IGNORED_OBJECTS: elif h4.text not in IGNORED_OBJECTS: # Or a type/object
test = check_object argvalues.append((check_object, h4))
names.append(h4.text)
if test:
def fn():
return test(h4)
fn.description = '{}({}) ({})'.format(test.__name__, h4.text, __name__)
yield fn
if __name__ == '__main__': @pytest.mark.parametrize(('method', 'data'), argvalues=argvalues, ids=names)
# Since we don't have the nice unittest asserts which show the comparison @pytest.mark.skipif(not sys.version_info >= (3, 5) or python_implementation() != 'CPython',
# We turn on debugging reason='follow_wrapped (inspect.signature) is not supported on this platform')
logging.basicConfig( def test_official(method, data):
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', method(data)
level=logging.DEBUG)
for f in test_official():
f()

View file

@ -5,65 +5,54 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
OrderInfo"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import ShippingAddress, OrderInfo
import telegram
from tests.base import BaseTest
class OrderInfoTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram OrderInfo.""" def order_info():
return OrderInfo(TestOrderInfo.name, TestOrderInfo.phone_number,
TestOrderInfo.email, TestOrderInfo.shipping_address)
def setUp(self):
self.name = 'name'
self.phone_number = 'phone_number'
self.email = 'email'
self.shipping_address = telegram.ShippingAddress('GB', '', 'London', '12 Grimmauld Place',
'', 'WC1')
self.json_dict = { class TestOrderInfo(object):
'name': self.name, name = 'name'
'phone_number': self.phone_number, phone_number = 'phone_number'
'email': self.email, email = 'email'
'shipping_address': self.shipping_address.to_dict() shipping_address = ShippingAddress('GB', '', 'London', '12 Grimmauld Place', '', 'WC1')
def test_de_json(self, bot):
json_dict = {
'name': TestOrderInfo.name,
'phone_number': TestOrderInfo.phone_number,
'email': TestOrderInfo.email,
'shipping_address': TestOrderInfo.shipping_address.to_dict()
} }
order_info = OrderInfo.de_json(json_dict, bot)
def test_orderinfo_de_json(self): assert order_info.name == self.name
orderinfo = telegram.OrderInfo.de_json(self.json_dict, self._bot) assert order_info.phone_number == self.phone_number
assert order_info.email == self.email
assert order_info.shipping_address == self.shipping_address
self.assertEqual(orderinfo.name, self.name) def test_to_dict(self, order_info):
self.assertEqual(orderinfo.phone_number, self.phone_number) order_info_dict = order_info.to_dict()
self.assertEqual(orderinfo.email, self.email)
self.assertEqual(orderinfo.shipping_address, self.shipping_address)
def test_orderinfo_to_json(self): assert isinstance(order_info_dict, dict)
orderinfo = telegram.OrderInfo.de_json(self.json_dict, self._bot) assert order_info_dict['name'] == order_info.name
assert order_info_dict['phone_number'] == order_info.phone_number
self.assertTrue(self.is_json(orderinfo.to_json())) assert order_info_dict['email'] == order_info.email
assert order_info_dict['shipping_address'] == order_info.shipping_address.to_dict()
def test_orderinfo_to_dict(self):
orderinfo = telegram.OrderInfo.de_json(self.json_dict, self._bot).to_dict()
self.assertTrue(self.is_dict(orderinfo))
self.assertDictEqual(self.json_dict, orderinfo)
if __name__ == '__main__':
unittest.main()

View file

@ -1,55 +1,38 @@
#!/usr/bin/env python #!/usr/bin/env python
# encoding: utf-8
# #
# A library that provides a Python interface to the Telegram Bot API # A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017 # Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram ParseMode"""
import sys from telegram import ParseMode
import unittest
sys.path.append('.')
import telegram
from tests.base import BaseTest
class ParseMode(BaseTest, unittest.TestCase): class TestParseMode(object):
"""This object represents Tests for Telegram ParseMode.""" markdown_text = '*bold* _italic_ [link](http://google.com).'
html_text = '<b>bold</b> <i>italic</i> <a href="http://google.com">link</a>.'
formatted_text_formatted = u'bold italic link.'
def setUp(self): def test_send_message_with_parse_mode_markdown(self, bot, chat_id):
self.markdown_text = "*bold* _italic_ [link](http://google.com)." message = bot.send_message(chat_id=chat_id, text=self.markdown_text,
self.html_text = '<b>bold</b> <i>italic</i> <a href="http://google.com">link</a>.' parse_mode=ParseMode.MARKDOWN)
self.formatted_text_formatted = u'bold italic link.'
def test_send_message_with_parse_mode_markdown(self): assert message.text == self.formatted_text_formatted
message = self._bot.sendMessage(
chat_id=self._chat_id, text=self.markdown_text, parse_mode=telegram.ParseMode.MARKDOWN)
self.assertTrue(self.is_json(message.to_json())) def test_send_message_with_parse_mode_html(self, bot, chat_id):
self.assertEqual(message.text, self.formatted_text_formatted) message = bot.send_message(chat_id=chat_id, text=self.html_text,
parse_mode=ParseMode.HTML)
def test_send_message_with_parse_mode_html(self): assert message.text == self.formatted_text_formatted
message = self._bot.sendMessage(
chat_id=self._chat_id, text=self.html_text, parse_mode=telegram.ParseMode.HTML)
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(message.text, self.formatted_text_formatted)
if __name__ == '__main__':
unittest.main()

View file

@ -5,305 +5,263 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram Photo"""
import os import os
import unittest
from io import BytesIO from io import BytesIO
import pytest
from flaky import flaky from flaky import flaky
import telegram from telegram import Sticker, TelegramError, PhotoSize, InputFile
from tests.base import BaseTest, timeout
class PhotoTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='function')
"""This object represents Tests for Telegram Photo.""" def photo_file():
f = open('tests/data/telegram.jpg', 'rb')
yield f
f.close()
@classmethod
def setUpClass(cls):
super(PhotoTest, cls).setUpClass()
cls.caption = u'PhotoTest - Caption' @pytest.fixture(scope='class')
cls.photo_file_url = 'https://python-telegram-bot.org/static/testfiles/telegram.jpg' def _photo(bot, chat_id):
with open('tests/data/telegram.jpg', 'rb') as f:
return bot.send_photo(chat_id, photo=f, timeout=10).photo
photo_file = open('tests/data/telegram.jpg', 'rb')
photo = cls._bot.send_photo(cls._chat_id, photo=photo_file, timeout=10).photo
cls.thumb, cls.photo = photo
@pytest.fixture(scope='class')
def thumb(_photo):
return _photo[0]
@pytest.fixture(scope='class')
def photo(_photo):
return _photo[1]
class TestPhoto(object):
width = 300
height = 300
caption = u'PhotoTest - Caption'
photo_file_url = 'https://python-telegram-bot.org/static/testfiles/telegram.jpg'
file_size = 10209
def test_creation(self, thumb, photo):
# Make sure file has been uploaded. # Make sure file has been uploaded.
# Simple assertions PY2 Only assert isinstance(photo, PhotoSize)
assert isinstance(cls.photo, telegram.PhotoSize) assert isinstance(photo.file_id, str)
assert isinstance(cls.thumb, telegram.PhotoSize) assert photo.file_id is not ''
assert isinstance(cls.photo.file_id, str)
assert isinstance(cls.thumb.file_id, str)
assert cls.photo.file_id is not ''
assert cls.thumb.file_id is not ''
def setUp(self): assert isinstance(thumb, PhotoSize)
self.photo_file = open('tests/data/telegram.jpg', 'rb') assert isinstance(thumb.file_id, str)
self.photo_bytes_jpg_no_standard = 'tests/data/telegram_no_standard_header.jpg' assert thumb.file_id is not ''
self.json_dict = {
'file_id': self.photo.file_id,
'width': self.photo.width,
'height': self.photo.height,
'file_size': self.photo.file_size
}
def test_expected_values(self): def test_expected_values(self, photo, thumb):
self.assertEqual(self.photo.width, 300) assert photo.width == self.width
self.assertEqual(self.photo.height, 300) assert photo.height == self.height
self.assertEqual(self.photo.file_size, 10209) assert photo.file_size == self.file_size
self.assertEqual(self.thumb.width, 90) assert thumb.width == 90
self.assertEqual(self.thumb.height, 90) assert thumb.height == 90
self.assertEqual(self.thumb.file_size, 1478) assert thumb.file_size == 1478
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_sendphoto_all_args(self): def test_send_photo_all_args(self, bot, chat_id, photo_file, thumb, photo):
message = self._bot.sendPhoto(self._chat_id, self.photo_file, caption=self.caption, disable_notification=False) message = bot.send_photo(chat_id, photo_file, caption=self.caption,
thumb, photo = message.photo disable_notification=False)
self.assertIsInstance(thumb, telegram.PhotoSize) assert isinstance(message.photo[0], PhotoSize)
self.assertIsInstance(thumb.file_id, str) assert isinstance(message.photo[0].file_id, str)
self.assertNotEqual(thumb.file_id, '') assert message.photo[0].file_id != ''
self.assertEqual(thumb.width, self.thumb.width) assert message.photo[0].width == thumb.width
self.assertEqual(thumb.height, self.thumb.height) assert message.photo[0].height == thumb.height
self.assertEqual(thumb.file_size, self.thumb.file_size) assert message.photo[0].file_size == thumb.file_size
self.assertIsInstance(photo, telegram.PhotoSize) assert isinstance(message.photo[1], PhotoSize)
self.assertIsInstance(photo.file_id, str) assert isinstance(message.photo[1].file_id, str)
self.assertNotEqual(photo.file_id, '') assert message.photo[1].file_id != ''
self.assertEqual(photo.width, self.photo.width) assert message.photo[1].width == photo.width
self.assertEqual(photo.height, self.photo.height) assert message.photo[1].height == photo.height
self.assertEqual(photo.file_size, self.photo.file_size) assert message.photo[1].file_size == photo.file_size
self.assertEqual(message.caption, self.caption) assert message.caption == TestPhoto.caption
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_get_and_download_photo(self): def test_get_and_download(self, bot, photo):
new_file = self._bot.getFile(self.photo.file_id) new_file = bot.getFile(photo.file_id)
self.assertEqual(new_file.file_size, self.photo.file_size) assert new_file.file_size == photo.file_size
self.assertEqual(new_file.file_id, self.photo.file_id) assert new_file.file_id == photo.file_id
self.assertTrue(new_file.file_path.startswith('https://')) assert new_file.file_path.startswith('https://') is True
new_file.download('telegram.jpg') new_file.download('telegram.jpg')
self.assertTrue(os.path.isfile('telegram.jpg')) assert os.path.isfile('telegram.jpg') is True
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_send_photo_url_jpg_file(self): def test_send_url_jpg_file(self, bot, chat_id, thumb, photo):
message = self._bot.sendPhoto(self._chat_id, photo=self.photo_file_url) message = bot.send_photo(chat_id, photo=self.photo_file_url)
thumb, photo = message.photo assert isinstance(message.photo[0], PhotoSize)
assert isinstance(message.photo[0].file_id, str)
assert message.photo[0].file_id != ''
assert message.photo[0].width == thumb.width
assert message.photo[0].height == thumb.height
assert message.photo[0].file_size == thumb.file_size
self.assertIsInstance(thumb, telegram.PhotoSize) assert isinstance(message.photo[1], PhotoSize)
self.assertIsInstance(thumb.file_id, str) assert isinstance(message.photo[1].file_id, str)
self.assertNotEqual(thumb.file_id, '') assert message.photo[1].file_id != ''
self.assertEqual(thumb.width, self.thumb.width) assert message.photo[1].width == photo.width
self.assertEqual(thumb.height, self.thumb.height) assert message.photo[1].height == photo.height
self.assertEqual(thumb.file_size, self.thumb.file_size) assert message.photo[1].file_size == photo.file_size
self.assertIsInstance(photo, telegram.PhotoSize)
self.assertIsInstance(photo.file_id, str)
self.assertNotEqual(photo.file_id, '')
self.assertEqual(photo.width, self.photo.width)
self.assertEqual(photo.height, self.photo.height)
self.assertEqual(photo.file_size, self.photo.file_size)
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_send_photo_url_png_file(self): def test_send_url_png_file(self, bot, chat_id):
message = self._bot.sendPhoto( message = bot.send_photo(photo='http://dummyimage.com/600x400/000/fff.png&text=telegram',
photo='http://dummyimage.com/600x400/000/fff.png&text=telegram', chat_id=self._chat_id) chat_id=chat_id)
photo = message.photo[-1] photo = message.photo[-1]
self.assertIsInstance(photo, telegram.PhotoSize) assert isinstance(photo, PhotoSize)
self.assertIsInstance(photo.file_id, str) assert isinstance(photo.file_id, str)
self.assertNotEqual(photo.file_id, '') assert photo.file_id != ''
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_send_photo_url_gif_file(self): def test_send_url_gif_file(self, bot, chat_id):
message = self._bot.sendPhoto( message = bot.send_photo(photo='http://dummyimage.com/600x400/000/fff.png&text=telegram',
photo='http://dummyimage.com/600x400/000/fff.png&text=telegram', chat_id=self._chat_id) chat_id=chat_id)
photo = message.photo[-1] photo = message.photo[-1]
self.assertIsInstance(photo, telegram.PhotoSize) assert isinstance(photo, PhotoSize)
self.assertIsInstance(photo.file_id, str) assert isinstance(photo.file_id, str)
self.assertNotEqual(photo.file_id, '') assert photo.file_id != ''
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_send_photo_bytesio_jpg_file(self): def test_send_bytesio_jpg_file(self, bot, chat_id):
file_name = 'tests/data/telegram_no_standard_header.jpg'
# raw image bytes # raw image bytes
raw_bytes = BytesIO(open(self.photo_bytes_jpg_no_standard, 'rb').read()) raw_bytes = BytesIO(open(file_name, 'rb').read())
inputfile = telegram.InputFile({"photo": raw_bytes}) inputfile = InputFile({'photo': raw_bytes})
self.assertEqual(inputfile.mimetype, 'application/octet-stream') assert inputfile.mimetype == 'application/octet-stream'
# raw image bytes with name info # raw image bytes with name info
raw_bytes = BytesIO(open(self.photo_bytes_jpg_no_standard, 'rb').read()) raw_bytes = BytesIO(open(file_name, 'rb').read())
raw_bytes.name = self.photo_bytes_jpg_no_standard raw_bytes.name = file_name
inputfile = telegram.InputFile({"photo": raw_bytes}) inputfile = InputFile({'photo': raw_bytes})
self.assertEqual(inputfile.mimetype, 'image/jpeg') assert inputfile.mimetype == 'image/jpeg'
# send raw photo # send raw photo
raw_bytes = BytesIO(open(self.photo_bytes_jpg_no_standard, 'rb').read()) raw_bytes = BytesIO(open(file_name, 'rb').read())
message = self._bot.sendPhoto(self._chat_id, photo=raw_bytes) message = bot.send_photo(chat_id, photo=raw_bytes)
photo = message.photo[-1] photo = message.photo[-1]
self.assertIsInstance(photo.file_id, str) assert isinstance(photo.file_id, str)
self.assertNotEqual(photo.file_id, '') assert photo.file_id != ''
self.assertIsInstance(photo, telegram.PhotoSize) assert isinstance(photo, PhotoSize)
self.assertEqual(photo.width, 1920) assert photo.width == 1920
self.assertEqual(photo.height, 1080) assert photo.height == 1080
self.assertEqual(photo.file_size, 30907) assert photo.file_size == 30907
def test_send_with_photosize(self, monkeypatch, bot, chat_id, photo):
def test(_, url, data, **kwargs):
return data['photo'] == photo.file_id
monkeypatch.setattr('telegram.utils.request.Request.post', test)
message = bot.send_photo(photo=photo, chat_id=chat_id)
assert message
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_silent_send_photo(self): def test_resend(self, bot, chat_id, photo):
message = self._bot.sendPhoto(photo=self.photo_file, chat_id=self._chat_id, message = bot.send_photo(chat_id=chat_id, photo=photo.file_id)
disable_notification=True)
thumb, photo = message.photo
self.assertIsInstance(thumb, telegram.PhotoSize)
self.assertIsInstance(thumb.file_id, str)
self.assertNotEqual(thumb.file_id, '')
self.assertIsInstance(photo, telegram.PhotoSize)
self.assertIsInstance(photo.file_id, str)
self.assertNotEqual(photo.file_id, '')
@flaky(3, 1)
@timeout(10)
def test_send_photo_with_photosize(self):
message = self._bot.send_photo(photo=self.photo, chat_id=self._chat_id)
thumb, photo = message.photo
self.assertEqual(photo, self.photo)
self.assertEqual(thumb, self.thumb)
@flaky(3, 1)
@timeout(10)
def test_send_photo_resend(self):
message = self._bot.sendPhoto(chat_id=self._chat_id, photo=self.photo.file_id)
thumb, photo = message.photo thumb, photo = message.photo
self.assertIsInstance(thumb, telegram.PhotoSize) assert isinstance(message.photo[0], PhotoSize)
self.assertEqual(thumb.file_id, self.thumb.file_id) assert isinstance(message.photo[0].file_id, str)
self.assertEqual(thumb.width, self.thumb.width) assert message.photo[0].file_id != ''
self.assertEqual(thumb.height, self.thumb.height) assert message.photo[0].width == thumb.width
self.assertEqual(thumb.file_size, self.thumb.file_size) assert message.photo[0].height == thumb.height
assert message.photo[0].file_size == thumb.file_size
self.assertIsInstance(photo, telegram.PhotoSize) assert isinstance(message.photo[1], PhotoSize)
self.assertEqual(photo.file_id, self.photo.file_id) assert isinstance(message.photo[1].file_id, str)
self.assertEqual(photo.width, self.photo.width) assert message.photo[1].file_id != ''
self.assertEqual(photo.height, self.photo.height) assert message.photo[1].width == photo.width
self.assertEqual(photo.file_size, self.photo.file_size) assert message.photo[1].height == photo.height
assert message.photo[1].file_size == photo.file_size
def test_photo_de_json(self): def test_de_json(self, bot, photo):
photo = telegram.PhotoSize.de_json(self.json_dict, self._bot) json_dict = {
'file_id': photo.file_id,
'width': self.width,
'height': self.height,
'file_size': self.file_size
}
json_photo = PhotoSize.de_json(json_dict, bot)
self.assertEqual(photo, self.photo) assert json_photo.file_id == photo.file_id
assert json_photo.width == self.width
assert json_photo.height == self.height
assert json_photo.file_size == self.file_size
def test_photo_to_json(self): def test_to_dict(self, photo):
self.assertTrue(self.is_json(self.photo.to_json())) photo_dict = photo.to_dict()
def test_photo_to_dict(self): assert isinstance(photo_dict, dict)
photo = self.photo.to_dict() assert photo_dict['file_id'] == photo.file_id
assert photo_dict['width'] == photo.width
self.assertTrue(self.is_dict(photo)) assert photo_dict['height'] == photo.height
self.assertEqual(photo['file_id'], self.photo.file_id) assert photo_dict['file_size'] == photo.file_size
self.assertEqual(photo['width'], self.photo.width)
self.assertEqual(photo['height'], self.photo.height)
self.assertEqual(photo['file_size'], self.photo.file_size)
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_error_send_photo_empty_file(self): def test_error_send_empty_file(self, bot, chat_id):
json_dict = self.json_dict with pytest.raises(TelegramError):
bot.send_photo(chat_id=chat_id, photo=open(os.devnull, 'rb'))
del (json_dict['file_id'])
json_dict['photo'] = open(os.devnull, 'rb')
with self.assertRaises(telegram.TelegramError):
self._bot.sendPhoto(chat_id=self._chat_id, **json_dict)
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_error_send_photo_empty_file_id(self): def test_error_send_empty_file_id(self, bot, chat_id):
json_dict = self.json_dict with pytest.raises(TelegramError):
bot.send_photo(chat_id=chat_id, photo='')
del (json_dict['file_id']) def test_error_without_required_args(self, bot, chat_id):
json_dict['photo'] = '' with pytest.raises(TypeError):
bot.send_photo(chat_id=chat_id)
with self.assertRaises(telegram.TelegramError): def test_equality(self, photo):
self._bot.sendPhoto(chat_id=self._chat_id, **json_dict) a = PhotoSize(photo.file_id, self.width, self.height)
b = PhotoSize(photo.file_id, self.width, self.height)
c = PhotoSize(photo.file_id, 0, 0)
d = PhotoSize('', self.width, self.height)
e = Sticker(photo.file_id, self.width, self.height)
@flaky(3, 1) assert a == b
@timeout(10) assert hash(a) == hash(b)
def test_error_photo_without_required_args(self): assert a is not b
json_dict = self.json_dict
del (json_dict['file_id']) assert a == c
del (json_dict['width']) assert hash(a) == hash(c)
del (json_dict['height'])
with self.assertRaises(TypeError): assert a != d
self._bot.sendPhoto(chat_id=self._chat_id, **json_dict) assert hash(a) != hash(d)
@flaky(3, 1) assert a != e
@timeout(10) assert hash(a) != hash(e)
def test_reply_photo(self):
"""Test for Message.reply_photo"""
message = self._bot.sendMessage(self._chat_id, '.')
thumb, photo = message.reply_photo(self.photo_file).photo
self.assertIsInstance(thumb, telegram.PhotoSize)
self.assertIsInstance(thumb.file_id, str)
self.assertNotEqual(thumb.file_id, '')
self.assertIsInstance(photo, telegram.PhotoSize)
self.assertIsInstance(photo.file_id, str)
self.assertNotEqual(photo.file_id, '')
def test_equality(self):
a = telegram.PhotoSize(self.photo.file_id, self.photo.width, self.photo.height)
b = telegram.PhotoSize(self.photo.file_id, self.photo.width, self.photo.height)
c = telegram.PhotoSize(self.photo.file_id, 0, 0)
d = telegram.PhotoSize("", self.photo.width, self.photo.height)
e = telegram.Sticker(self.photo.file_id, self.photo.width, self.photo.height)
self.assertEqual(a, b)
self.assertEqual(hash(a), hash(b))
self.assertIsNot(a, b)
self.assertEqual(a, c)
self.assertEqual(hash(a), hash(c))
self.assertNotEqual(a, d)
self.assertNotEqual(hash(a), hash(d))
self.assertNotEqual(a, e)
self.assertNotEqual(hash(a), hash(e))
if __name__ == '__main__':
unittest.main()

View file

@ -5,43 +5,47 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
PreCheckoutQuery"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import Update, User, PreCheckoutQuery, OrderInfo
import telegram
from tests.base import BaseTest
class PreCheckoutQueryTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram PreCheckoutQuery.""" def pre_checkout_query(bot):
return PreCheckoutQuery(TestPreCheckoutQuery.id,
TestPreCheckoutQuery.from_user,
TestPreCheckoutQuery.currency,
TestPreCheckoutQuery.total_amount,
TestPreCheckoutQuery.invoice_payload,
shipping_option_id=TestPreCheckoutQuery.shipping_option_id,
order_info=TestPreCheckoutQuery.order_info,
bot=bot)
def setUp(self):
self._id = 5
self.invoice_payload = 'invoice_payload'
self.shipping_option_id = 'shipping_option_id'
self.currency = 'EUR'
self.total_amount = 100
self.from_user = telegram.User(0, '')
self.order_info = telegram.OrderInfo()
self.json_dict = { class TestPreCheckoutQuery(object):
'id': self._id, id = 5
invoice_payload = 'invoice_payload'
shipping_option_id = 'shipping_option_id'
currency = 'EUR'
total_amount = 100
from_user = User(0, '')
order_info = OrderInfo()
def test_de_json(self, bot):
json_dict = {
'id': self.id,
'invoice_payload': self.invoice_payload, 'invoice_payload': self.invoice_payload,
'shipping_option_id': self.shipping_option_id, 'shipping_option_id': self.shipping_option_id,
'currency': self.currency, 'currency': self.currency,
@ -49,51 +53,53 @@ class PreCheckoutQueryTest(BaseTest, unittest.TestCase):
'from': self.from_user.to_dict(), 'from': self.from_user.to_dict(),
'order_info': self.order_info.to_dict() 'order_info': self.order_info.to_dict()
} }
pre_checkout_query = PreCheckoutQuery.de_json(json_dict, bot)
def test_precheckoutquery_de_json(self): assert pre_checkout_query.id == self.id
precheckoutquery = telegram.PreCheckoutQuery.de_json(self.json_dict, self._bot) assert pre_checkout_query.invoice_payload == self.invoice_payload
assert pre_checkout_query.shipping_option_id == self.shipping_option_id
assert pre_checkout_query.currency == self.currency
assert pre_checkout_query.from_user == self.from_user
assert pre_checkout_query.order_info == self.order_info
self.assertEqual(precheckoutquery.id, self._id) def test_to_dict(self, pre_checkout_query):
self.assertEqual(precheckoutquery.invoice_payload, self.invoice_payload) pre_checkout_query_dict = pre_checkout_query.to_dict()
self.assertEqual(precheckoutquery.shipping_option_id, self.shipping_option_id)
self.assertEqual(precheckoutquery.currency, self.currency)
self.assertEqual(precheckoutquery.from_user, self.from_user)
self.assertEqual(precheckoutquery.order_info, self.order_info)
def test_precheckoutquery_to_json(self): assert isinstance(pre_checkout_query_dict, dict)
precheckoutquery = telegram.PreCheckoutQuery.de_json(self.json_dict, self._bot) assert pre_checkout_query_dict['id'] == pre_checkout_query.id
assert pre_checkout_query_dict['invoice_payload'] == pre_checkout_query.invoice_payload
assert pre_checkout_query_dict['shipping_option_id'] == \
pre_checkout_query.shipping_option_id
assert pre_checkout_query_dict['currency'] == pre_checkout_query.currency
assert pre_checkout_query_dict['from'] == pre_checkout_query.from_user.to_dict()
assert pre_checkout_query_dict['order_info'] == pre_checkout_query.order_info.to_dict()
self.assertTrue(self.is_json(precheckoutquery.to_json())) def test_answer(self, monkeypatch, pre_checkout_query):
def test(*args, **kwargs):
return args[1] == pre_checkout_query.id
def test_precheckoutquery_to_dict(self): monkeypatch.setattr('telegram.Bot.answer_pre_checkout_query', test)
precheckoutquery = telegram.PreCheckoutQuery.de_json(self.json_dict, self._bot).to_dict() assert pre_checkout_query.answer()
self.assertTrue(self.is_dict(precheckoutquery))
self.assertDictEqual(self.json_dict, precheckoutquery)
def test_equality(self): def test_equality(self):
a = telegram.PreCheckoutQuery(self._id, self.from_user, self.currency, self.total_amount, a = PreCheckoutQuery(self.id, self.from_user, self.currency, self.total_amount,
self.invoice_payload) self.invoice_payload)
b = telegram.PreCheckoutQuery(self._id, self.from_user, self.currency, self.total_amount, b = PreCheckoutQuery(self.id, self.from_user, self.currency, self.total_amount,
self.invoice_payload) self.invoice_payload)
c = telegram.PreCheckoutQuery(self._id, None, '', 0, '') c = PreCheckoutQuery(self.id, None, '', 0, '')
d = telegram.PreCheckoutQuery(0, self.from_user, self.currency, self.total_amount, d = PreCheckoutQuery(0, self.from_user, self.currency, self.total_amount,
self.invoice_payload) self.invoice_payload)
e = telegram.Update(self._id) e = Update(self.id)
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertEqual(a, c) assert a == c
self.assertEqual(hash(a), hash(c)) assert hash(a) == hash(c)
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
self.assertNotEqual(a, e) assert a != e
self.assertNotEqual(hash(a), hash(e)) assert hash(a) != hash(e)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,138 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
import pytest
from telegram import (Update, Chat, Bot, ChosenInlineResult, User, Message, CallbackQuery,
InlineQuery, ShippingQuery, PreCheckoutQuery)
from telegram.ext import PreCheckoutQueryHandler
message = Message(1, User(1, ''), None, Chat(1, ''), text='Text')
params = [
{'message': message},
{'edited_message': message},
{'callback_query': CallbackQuery(1, User(1, ''), 'chat', message=message)},
{'channel_post': message},
{'edited_channel_post': message},
{'inline_query': InlineQuery(1, User(1, ''), '', '')},
{'chosen_inline_result': ChosenInlineResult('id', User(1, ''), '')},
{'shipping_query': ShippingQuery('id', User(1, ''), '', None)},
{'callback_query': CallbackQuery(1, User(1, ''), 'chat')}
]
ids = ('message', 'edited_message', 'callback_query', 'channel_post',
'edited_channel_post', 'inline_query', 'chosen_inline_result',
'shipping_query', 'callback_query_without_message')
@pytest.fixture(scope='class', params=params, ids=ids)
def false_update(request):
return Update(update_id=1, **request.param)
@pytest.fixture(scope='class')
def pre_checkout_query():
return Update(1, pre_checkout_query=PreCheckoutQuery('id', User(1, 'test user'), 'EUR', 223,
'invoice_payload'))
class TestPreCheckoutQueryHandler(object):
test_flag = False
@pytest.fixture(autouse=True)
def reset(self):
self.test_flag = False
def callback_basic(self, bot, update):
test_bot = isinstance(bot, Bot)
test_update = isinstance(update, Update)
self.test_flag = test_bot and test_update
def callback_data_1(self, bot, update, user_data=None, chat_data=None):
self.test_flag = (user_data is not None) or (chat_data is not None)
def callback_data_2(self, bot, update, user_data=None, chat_data=None):
self.test_flag = (user_data is not None) and (chat_data is not None)
def callback_queue_1(self, bot, update, job_queue=None, update_queue=None):
self.test_flag = (job_queue is not None) or (update_queue is not None)
def callback_queue_2(self, bot, update, job_queue=None, update_queue=None):
self.test_flag = (job_queue is not None) and (update_queue is not None)
def test_basic(self, dp, pre_checkout_query):
handler = PreCheckoutQueryHandler(self.callback_basic)
dp.add_handler(handler)
assert handler.check_update(pre_checkout_query)
dp.process_update(pre_checkout_query)
assert self.test_flag
def test_pass_user_or_chat_data(self, dp, pre_checkout_query):
handler = PreCheckoutQueryHandler(self.callback_data_1, pass_user_data=True)
dp.add_handler(handler)
dp.process_update(pre_checkout_query)
assert self.test_flag
dp.remove_handler(handler)
handler = PreCheckoutQueryHandler(self.callback_data_1, pass_chat_data=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(pre_checkout_query)
assert self.test_flag
dp.remove_handler(handler)
handler = PreCheckoutQueryHandler(self.callback_data_2, pass_chat_data=True,
pass_user_data=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(pre_checkout_query)
assert self.test_flag
def test_pass_job_or_update_queue(self, dp, pre_checkout_query):
handler = PreCheckoutQueryHandler(self.callback_queue_1, pass_job_queue=True)
dp.add_handler(handler)
dp.process_update(pre_checkout_query)
assert self.test_flag
dp.remove_handler(handler)
handler = PreCheckoutQueryHandler(self.callback_queue_1, pass_update_queue=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(pre_checkout_query)
assert self.test_flag
dp.remove_handler(handler)
handler = PreCheckoutQueryHandler(self.callback_queue_2, pass_job_queue=True,
pass_update_queue=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(pre_checkout_query)
assert self.test_flag
def test_other_update_types(self, false_update):
handler = PreCheckoutQueryHandler(self.callback_basic)
assert not handler.check_update(false_update)

206
tests/test_regexhandler.py Normal file
View file

@ -0,0 +1,206 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
import pytest
from telegram import (Message, Update, Chat, Bot, User, CallbackQuery, InlineQuery,
ChosenInlineResult, ShippingQuery, PreCheckoutQuery)
from telegram.ext import RegexHandler
message = Message(1, User(1, ''), None, Chat(1, ''), text='Text')
params = [
{'callback_query': CallbackQuery(1, User(1, ''), 'chat', message=message)},
{'inline_query': InlineQuery(1, User(1, ''), '', '')},
{'chosen_inline_result': ChosenInlineResult('id', User(1, ''), '')},
{'shipping_query': ShippingQuery('id', User(1, ''), '', None)},
{'pre_checkout_query': PreCheckoutQuery('id', User(1, ''), '', 0, '')},
{'callback_query': CallbackQuery(1, User(1, ''), 'chat')}
]
ids = ('callback_query', 'inline_query', 'chosen_inline_result',
'shipping_query', 'pre_checkout_query', 'callback_query_without_message')
@pytest.fixture(scope='class', params=params, ids=ids)
def false_update(request):
return Update(update_id=1, **request.param)
@pytest.fixture(scope='class')
def message(bot):
return Message(1, None, None, None, text='test message', bot=bot)
class TestRegexHandler(object):
test_flag = False
@pytest.fixture(autouse=True)
def reset(self):
self.test_flag = False
def callback_basic(self, bot, update):
test_bot = isinstance(bot, Bot)
test_update = isinstance(update, Update)
self.test_flag = test_bot and test_update
def callback_data_1(self, bot, update, user_data=None, chat_data=None):
self.test_flag = (user_data is not None) or (chat_data is not None)
def callback_data_2(self, bot, update, user_data=None, chat_data=None):
self.test_flag = (user_data is not None) and (chat_data is not None)
def callback_queue_1(self, bot, update, job_queue=None, update_queue=None):
self.test_flag = (job_queue is not None) or (update_queue is not None)
def callback_queue_2(self, bot, update, job_queue=None, update_queue=None):
self.test_flag = (job_queue is not None) and (update_queue is not None)
def callback_group(self, bot, update, groups=None, groupdict=None):
if groups is not None:
self.test_flag = groups == ('t', ' message')
if groupdict is not None:
self.test_flag = groupdict == {'begin': 't', 'end': ' message'}
def test_basic(self, dp, message):
handler = RegexHandler('.*', self.callback_basic)
dp.add_handler(handler)
assert handler.check_update(Update(0, message))
dp.process_update(Update(0, message))
assert self.test_flag
def test_pattern(self, message):
handler = RegexHandler('.*est.*', self.callback_basic)
assert handler.check_update(Update(0, message))
handler = RegexHandler('.*not in here.*', self.callback_basic)
assert not handler.check_update(Update(0, message))
def test_with_passing_group_dict(self, dp, message):
handler = RegexHandler('(?P<begin>.*)est(?P<end>.*)', self.callback_group,
pass_groups=True)
dp.add_handler(handler)
dp.process_update(Update(0, message))
assert self.test_flag
dp.remove_handler(handler)
handler = RegexHandler('(?P<begin>.*)est(?P<end>.*)', self.callback_group,
pass_groupdict=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(Update(0, message))
assert self.test_flag
def test_edited(self, message):
handler = RegexHandler('.*', self.callback_basic, edited_updates=True,
message_updates=False, channel_post_updates=False)
assert handler.check_update(Update(0, edited_message=message))
assert not handler.check_update(Update(0, message=message))
assert not handler.check_update(Update(0, channel_post=message))
assert not handler.check_update(Update(0, edited_channel_post=message))
def test_channel_post(self, message):
handler = RegexHandler('.*', self.callback_basic, edited_updates=False,
message_updates=False, channel_post_updates=True)
assert not handler.check_update(Update(0, edited_message=message))
assert not handler.check_update(Update(0, message=message))
assert handler.check_update(Update(0, channel_post=message))
assert not handler.check_update(Update(0, edited_channel_post=message))
def test_multiple_flags(self, message):
handler = RegexHandler('.*', self.callback_basic, edited_updates=True,
message_updates=True, channel_post_updates=True)
assert handler.check_update(Update(0, edited_message=message))
assert handler.check_update(Update(0, message=message))
assert handler.check_update(Update(0, channel_post=message))
assert not handler.check_update(Update(0, edited_channel_post=message))
def test_allow_updated(self, message):
with pytest.warns(UserWarning):
handler = RegexHandler('.*', self.callback_basic, message_updates=True,
allow_edited=True)
assert handler.check_update(Update(0, edited_message=message))
assert handler.check_update(Update(0, message=message))
assert not handler.check_update(Update(0, channel_post=message))
assert not handler.check_update(Update(0, edited_channel_post=message))
def test_none_allowed(self):
with pytest.raises(ValueError, match='are all False'):
handler = RegexHandler('.*', self.callback_basic, message_updates=False,
channel_post_updates=False, edited_updates=False)
def test_pass_user_or_chat_data(self, dp, message):
handler = RegexHandler('.*', self.callback_data_1, pass_user_data=True)
dp.add_handler(handler)
dp.process_update(Update(0, message=message))
assert self.test_flag
dp.remove_handler(handler)
handler = RegexHandler('.*', self.callback_data_1, pass_chat_data=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(Update(0, message=message))
assert self.test_flag
dp.remove_handler(handler)
handler = RegexHandler('.*', self.callback_data_2, pass_chat_data=True,
pass_user_data=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(Update(0, message=message))
assert self.test_flag
def test_pass_job_or_update_queue(self, dp, message):
handler = RegexHandler('.*', self.callback_queue_1, pass_job_queue=True)
dp.add_handler(handler)
dp.process_update(Update(0, message=message))
assert self.test_flag
dp.remove_handler(handler)
handler = RegexHandler('.*', self.callback_queue_1, pass_update_queue=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(Update(0, message=message))
assert self.test_flag
dp.remove_handler(handler)
handler = RegexHandler('.*', self.callback_queue_2, pass_job_queue=True,
pass_update_queue=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(Update(0, message=message))
assert self.test_flag
def test_other_update_types(self, false_update):
handler = RegexHandler('.*', self.callback_basic, edited_updates=True)
assert not handler.check_update(false_update)

View file

@ -1,86 +1,74 @@
#!/usr/bin/env python #!/usr/bin/env python
# encoding: utf-8
# #
# A library that provides a Python interface to the Telegram Bot API # A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017 # Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram ReplyKeyboardMarkup"""
import sys import pytest
import unittest from flaky import flaky
sys.path.append('.') from telegram import ReplyKeyboardMarkup, KeyboardButton
import telegram
from tests.base import BaseTest
class ReplyKeyboardMarkupTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram ReplyKeyboardMarkup.""" def reply_keyboard_markup():
return ReplyKeyboardMarkup(TestReplyKeyboardMarkup.keyboard,
def setUp(self): resize_keyboard=TestReplyKeyboardMarkup.resize_keyboard,
self.keyboard = [[telegram.KeyboardButton('button1'), telegram.KeyboardButton('button2')]] one_time_keyboard=TestReplyKeyboardMarkup.one_time_keyboard,
self.resize_keyboard = True selective=TestReplyKeyboardMarkup.selective)
self.one_time_keyboard = True
self.selective = True
self.json_dict = {
'keyboard': [[self.keyboard[0][0].to_dict(), self.keyboard[0][1].to_dict()]],
'resize_keyboard': self.resize_keyboard,
'one_time_keyboard': self.one_time_keyboard,
'selective': self.selective,
}
def test_send_message_with_reply_keyboard_markup(self):
message = self._bot.sendMessage(
self._chat_id,
'Моё судно на воздушной подушке полно угрей',
reply_markup=telegram.ReplyKeyboardMarkup.de_json(self.json_dict, self._bot))
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(message.text, u'Моё судно на воздушной подушке полно угрей')
def test_reply_markup_empty_de_json_empty(self):
reply_markup_empty = telegram.ReplyKeyboardMarkup.de_json(None, self._bot)
self.assertFalse(reply_markup_empty)
def test_reply_keyboard_markup_de_json(self):
reply_keyboard_markup = telegram.ReplyKeyboardMarkup.de_json(self.json_dict, self._bot)
self.assertTrue(isinstance(reply_keyboard_markup.keyboard, list))
self.assertTrue(isinstance(reply_keyboard_markup.keyboard[0][0], telegram.KeyboardButton))
self.assertEqual(reply_keyboard_markup.resize_keyboard, self.resize_keyboard)
self.assertEqual(reply_keyboard_markup.one_time_keyboard, self.one_time_keyboard)
self.assertEqual(reply_keyboard_markup.selective, self.selective)
def test_reply_keyboard_markup_to_json(self):
reply_keyboard_markup = telegram.ReplyKeyboardMarkup.de_json(self.json_dict, self._bot)
self.assertTrue(self.is_json(reply_keyboard_markup.to_json()))
def test_reply_keyboard_markup_to_dict(self):
reply_keyboard_markup = telegram.ReplyKeyboardMarkup.de_json(self.json_dict, self._bot)
self.assertTrue(isinstance(reply_keyboard_markup.keyboard, list))
self.assertTrue(isinstance(reply_keyboard_markup.keyboard[0][0], telegram.KeyboardButton))
self.assertEqual(reply_keyboard_markup['resize_keyboard'], self.resize_keyboard)
self.assertEqual(reply_keyboard_markup['one_time_keyboard'], self.one_time_keyboard)
self.assertEqual(reply_keyboard_markup['selective'], self.selective)
if __name__ == '__main__': class TestReplyKeyboardMarkup(object):
unittest.main() keyboard = [[KeyboardButton('button1'), KeyboardButton('button2')]]
resize_keyboard = True
one_time_keyboard = True
selective = True
@flaky(3, 1)
@pytest.mark.timeout(10)
def test_send_message_with_reply_keyboard_markup(self, bot, chat_id, reply_keyboard_markup):
message = bot.send_message(chat_id, 'Text', reply_markup=reply_keyboard_markup)
assert message.text == 'Text'
@flaky(3, 1)
@pytest.mark.timeout(10)
def test_send_message_with_data_markup(self, bot, chat_id):
message = bot.send_message(chat_id, 'text 2', reply_markup={'keyboard': [['1', '2']]})
assert message.text == 'text 2'
def test_expected_values(self, reply_keyboard_markup):
assert isinstance(reply_keyboard_markup.keyboard, list)
assert isinstance(reply_keyboard_markup.keyboard[0][0], KeyboardButton)
assert isinstance(reply_keyboard_markup.keyboard[0][1], KeyboardButton)
assert reply_keyboard_markup.resize_keyboard == self.resize_keyboard
assert reply_keyboard_markup.one_time_keyboard == self.one_time_keyboard
assert reply_keyboard_markup.selective == self.selective
def test_to_dict(self, reply_keyboard_markup):
reply_keyboard_markup_dict = reply_keyboard_markup.to_dict()
assert isinstance(reply_keyboard_markup_dict, dict)
assert reply_keyboard_markup_dict['keyboard'][0][0] == \
reply_keyboard_markup.keyboard[0][0].to_dict()
assert reply_keyboard_markup_dict['keyboard'][0][1] == \
reply_keyboard_markup.keyboard[0][1].to_dict()
assert reply_keyboard_markup_dict['resize_keyboard'] == \
reply_keyboard_markup.resize_keyboard
assert reply_keyboard_markup_dict['one_time_keyboard'] == \
reply_keyboard_markup.one_time_keyboard
assert reply_keyboard_markup_dict['selective'] == reply_keyboard_markup.selective

View file

@ -1,76 +1,48 @@
#!/usr/bin/env python #!/usr/bin/env python
# encoding: utf-8
# #
# A library that provides a Python interface to the Telegram Bot API # A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017 # Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram ReplyKeyboardRemove"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import ReplyKeyboardRemove
import telegram
from tests.base import BaseTest
class ReplyKeyboardRemoveTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram ReplyKeyboardRemove.""" def reply_keyboard_remove():
return ReplyKeyboardRemove(selective=TestReplyKeyboardRemove.selective)
def setUp(self):
self.remove_keyboard = True
self.selective = True
self.json_dict = {
'remove_keyboard': self.remove_keyboard,
'selective': self.selective,
}
def test_send_message_with_reply_keyboard_remove(self):
message = self._bot.sendMessage(
self._chat_id,
'Моё судно на воздушной подушке полно угрей',
reply_markup=telegram.ReplyKeyboardRemove.de_json(self.json_dict, self._bot))
self.assertTrue(self.is_json(message.to_json()))
self.assertEqual(message.text, u'Моё судно на воздушной подушке полно угрей')
def test_reply_keyboard_remove_de_json(self):
reply_keyboard_remove = telegram.ReplyKeyboardRemove.de_json(self.json_dict, self._bot)
self.assertEqual(reply_keyboard_remove.remove_keyboard, self.remove_keyboard)
self.assertEqual(reply_keyboard_remove.selective, self.selective)
def test_reply_keyboard_remove_de_json_empty(self):
reply_keyboard_remove = telegram.ReplyKeyboardRemove.de_json(None, self._bot)
self.assertFalse(reply_keyboard_remove)
def test_reply_keyboard_remove_to_json(self):
reply_keyboard_remove = telegram.ReplyKeyboardRemove.de_json(self.json_dict, self._bot)
self.assertTrue(self.is_json(reply_keyboard_remove.to_json()))
def test_reply_keyboard_remove_to_dict(self):
reply_keyboard_remove = telegram.ReplyKeyboardRemove.de_json(self.json_dict, self._bot)
self.assertEqual(reply_keyboard_remove['remove_keyboard'], self.remove_keyboard)
self.assertEqual(reply_keyboard_remove['selective'], self.selective)
if __name__ == '__main__': class TestReplyKeyboardRemove(object):
unittest.main() remove_keyboard = True
selective = True
def test_send_message_with_reply_keyboard_remove(self, bot, chat_id, reply_keyboard_remove):
message = bot.send_message(chat_id, 'Text', reply_markup=reply_keyboard_remove)
assert message.text == 'Text'
def test_expected_values(self, reply_keyboard_remove):
assert reply_keyboard_remove.remove_keyboard == self.remove_keyboard
assert reply_keyboard_remove.selective == self.selective
def test_to_dict(self, reply_keyboard_remove):
reply_keyboard_remove_dict = reply_keyboard_remove.to_dict()
assert reply_keyboard_remove_dict['remove_keyboard'] == \
reply_keyboard_remove.remove_keyboard
assert reply_keyboard_remove_dict['selective'] == reply_keyboard_remove.selective

View file

@ -1,41 +0,0 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
ReplyMarkup"""
import sys
import unittest
sys.path.append('.')
import telegram
from tests.base import BaseTest
class ReplyMarkupTest(BaseTest, unittest.TestCase):
"""This object represents Tests for Telegram ReplyMarkup."""
def test_reply_markup_de_json_empty(self):
reply_markup = telegram.ReplyMarkup.de_json(None, self._bot)
self.assertFalse(reply_markup)
if __name__ == '__main__':
unittest.main()

View file

@ -5,41 +5,43 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
ShippingAddress"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import ShippingAddress
import telegram
from tests.base import BaseTest
class ShippingAddressTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram ShippingAddress.""" def shipping_address():
return ShippingAddress(TestShippingAddress.country_code,
TestShippingAddress.state,
TestShippingAddress.city,
TestShippingAddress.street_line1,
TestShippingAddress.street_line2,
TestShippingAddress.post_code)
def setUp(self):
self.country_code = 'GB'
self.state = 'state'
self.city = 'London'
self.street_line1 = '12 Grimmauld Place'
self.street_line2 = 'street_line2'
self.post_code = 'WC1'
self.json_dict = { class TestShippingAddress(object):
country_code = 'GB'
state = 'state'
city = 'London'
street_line1 = '12 Grimmauld Place'
street_line2 = 'street_line2'
post_code = 'WC1'
def test_de_json(self, bot):
json_dict = {
'country_code': self.country_code, 'country_code': self.country_code,
'state': self.state, 'state': self.state,
'city': self.city, 'city': self.city,
@ -47,68 +49,62 @@ class ShippingAddressTest(BaseTest, unittest.TestCase):
'street_line2': self.street_line2, 'street_line2': self.street_line2,
'post_code': self.post_code 'post_code': self.post_code
} }
shipping_address = ShippingAddress.de_json(json_dict, bot)
def test_shippingaddress_de_json(self): assert shipping_address.country_code == self.country_code
shippingaddress = telegram.ShippingAddress.de_json(self.json_dict, self._bot) assert shipping_address.state == self.state
assert shipping_address.city == self.city
assert shipping_address.street_line1 == self.street_line1
assert shipping_address.street_line2 == self.street_line2
assert shipping_address.post_code == self.post_code
self.assertEqual(shippingaddress.country_code, self.country_code) def test_to_dict(self, shipping_address):
self.assertEqual(shippingaddress.state, self.state) shipping_address_dict = shipping_address.to_dict()
self.assertEqual(shippingaddress.city, self.city)
self.assertEqual(shippingaddress.street_line1, self.street_line1)
self.assertEqual(shippingaddress.street_line2, self.street_line2)
self.assertEqual(shippingaddress.post_code, self.post_code)
def test_shippingaddress_to_json(self): assert isinstance(shipping_address_dict, dict)
shippingaddress = telegram.ShippingAddress.de_json(self.json_dict, self._bot) assert shipping_address_dict['country_code'] == shipping_address.country_code
assert shipping_address_dict['state'] == shipping_address.state
self.assertTrue(self.is_json(shippingaddress.to_json())) assert shipping_address_dict['city'] == shipping_address.city
assert shipping_address_dict['street_line1'] == shipping_address.street_line1
def test_shippingaddress_to_dict(self): assert shipping_address_dict['street_line2'] == shipping_address.street_line2
shippingaddress = telegram.ShippingAddress.de_json(self.json_dict, self._bot).to_dict() assert shipping_address_dict['post_code'] == shipping_address.post_code
self.assertTrue(self.is_dict(shippingaddress))
self.assertDictEqual(self.json_dict, shippingaddress)
def test_equality(self): def test_equality(self):
a = telegram.ShippingAddress(self.country_code, self.state, self.city, self.street_line1, a = ShippingAddress(self.country_code, self.state, self.city, self.street_line1,
self.street_line2, self.post_code) self.street_line2, self.post_code)
b = telegram.ShippingAddress(self.country_code, self.state, self.city, self.street_line1, b = ShippingAddress(self.country_code, self.state, self.city, self.street_line1,
self.street_line2, self.post_code) self.street_line2, self.post_code)
d = telegram.ShippingAddress('', self.state, self.city, self.street_line1, d = ShippingAddress('', self.state, self.city, self.street_line1,
self.street_line2, self.post_code) self.street_line2, self.post_code)
d2 = telegram.ShippingAddress(self.country_code, '', self.city, self.street_line1, d2 = ShippingAddress(self.country_code, '', self.city, self.street_line1,
self.street_line2, self.post_code) self.street_line2, self.post_code)
d3 = telegram.ShippingAddress(self.country_code, self.state, '', self.street_line1, d3 = ShippingAddress(self.country_code, self.state, '', self.street_line1,
self.street_line2, self.post_code) self.street_line2, self.post_code)
d4 = telegram.ShippingAddress(self.country_code, self.state, self.city, '', d4 = ShippingAddress(self.country_code, self.state, self.city, '',
self.street_line2, self.post_code) self.street_line2, self.post_code)
d5 = telegram.ShippingAddress(self.country_code, self.state, self.city, self.street_line1, d5 = ShippingAddress(self.country_code, self.state, self.city, self.street_line1,
'', self.post_code) '', self.post_code)
d6 = telegram.ShippingAddress(self.country_code, self.state, self.city, self.street_line1, d6 = ShippingAddress(self.country_code, self.state, self.city, self.street_line1,
self.street_line2, '') self.street_line2, '')
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
self.assertNotEqual(a, d2) assert a != d2
self.assertNotEqual(hash(a), hash(d2)) assert hash(a) != hash(d2)
self.assertNotEqual(a, d3) assert a != d3
self.assertNotEqual(hash(a), hash(d3)) assert hash(a) != hash(d3)
self.assertNotEqual(a, d4) assert a != d4
self.assertNotEqual(hash(a), hash(d4)) assert hash(a) != hash(d4)
self.assertNotEqual(a, d5) assert a != d5
self.assertNotEqual(hash(a), hash(d5)) assert hash(a) != hash(d5)
self.assertNotEqual(a, d6) assert a != d6
self.assertNotEqual(hash(6), hash(d6)) assert hash(6) != hash(d6)
if __name__ == '__main__':
unittest.main()

View file

@ -5,84 +5,67 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
ShippingOption"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import LabeledPrice, ShippingOption, Voice
import telegram
from tests.base import BaseTest
class ShippingOptionTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram ShippingOption.""" def shipping_option():
return ShippingOption(TestShippingOption.id, TestShippingOption.title,
TestShippingOption.prices)
def setUp(self):
self._id = 'id' class TestShippingOption(object):
self.title = 'title' id = 'id'
self.prices = [ title = 'title'
telegram.LabeledPrice('Fish Container', 100), prices = [
telegram.LabeledPrice('Premium Fish Container', 1000) LabeledPrice('Fish Container', 100),
LabeledPrice('Premium Fish Container', 1000)
] ]
self.json_dict = { def test_expected_values(self, shipping_option):
'id': self._id, assert shipping_option.id == self.id
'title': self.title, assert shipping_option.title == self.title
'prices': [x.to_dict() for x in self.prices] assert shipping_option.prices == self.prices
}
def test_shippingoption_de_json(self): def test_to_dict(self, shipping_option):
shippingoption = telegram.ShippingOption.de_json(self.json_dict, self._bot) shipping_option_dict = shipping_option.to_dict()
self.assertEqual(shippingoption.id, self._id) assert isinstance(shipping_option_dict, dict)
self.assertEqual(shippingoption.title, self.title) assert shipping_option_dict['id'] == shipping_option.id
self.assertEqual(shippingoption.prices, self.prices) assert shipping_option_dict['title'] == shipping_option.title
assert shipping_option_dict['prices'][0] == shipping_option.prices[0].to_dict()
def test_shippingoption_to_json(self): assert shipping_option_dict['prices'][1] == shipping_option.prices[1].to_dict()
shippingoption = telegram.ShippingOption.de_json(self.json_dict, self._bot)
self.assertTrue(self.is_json(shippingoption.to_json()))
def test_shippingoption_to_dict(self):
shippingoption = telegram.ShippingOption.de_json(self.json_dict, self._bot).to_dict()
self.assertTrue(self.is_dict(shippingoption))
self.assertDictEqual(self.json_dict, shippingoption)
def test_equality(self): def test_equality(self):
a = telegram.ShippingOption(self._id, self.title, self.prices) a = ShippingOption(self.id, self.title, self.prices)
b = telegram.ShippingOption(self._id, self.title, self.prices) b = ShippingOption(self.id, self.title, self.prices)
c = telegram.ShippingOption(self._id, '', []) c = ShippingOption(self.id, '', [])
d = telegram.ShippingOption(0, self.title, self.prices) d = ShippingOption(0, self.title, self.prices)
e = telegram.Voice(self._id, 0) e = Voice(self.id, 0)
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertEqual(a, c) assert a == c
self.assertEqual(hash(a), hash(c)) assert hash(a) == hash(c)
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
self.assertNotEqual(a, e) assert a != e
self.assertNotEqual(hash(a), hash(e)) assert hash(a) != hash(e)
if __name__ == '__main__':
unittest.main()

View file

@ -5,87 +5,84 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
ShippingQuery"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import Update, User, ShippingAddress, ShippingQuery
import telegram
from tests.base import BaseTest
class ShippingQueryTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram ShippingQuery.""" def shipping_query(bot):
return ShippingQuery(TestShippingQuery.id,
TestShippingQuery.from_user,
TestShippingQuery.invoice_payload,
TestShippingQuery.shipping_address,
bot=bot)
def setUp(self):
self._id = 5
self.invoice_payload = 'invoice_payload'
self.from_user = telegram.User(0, '')
self.shipping_address = telegram.ShippingAddress('GB', '', 'London', '12 Grimmauld Place',
'', 'WC1')
self.json_dict = { class TestShippingQuery(object):
'id': self._id, id = 5
'invoice_payload': self.invoice_payload, invoice_payload = 'invoice_payload'
'from': self.from_user.to_dict(), from_user = User(0, '')
'shipping_address': self.shipping_address.to_dict() shipping_address = ShippingAddress('GB', '', 'London', '12 Grimmauld Place', '', 'WC1')
def test_de_json(self, bot):
json_dict = {
'id': TestShippingQuery.id,
'invoice_payload': TestShippingQuery.invoice_payload,
'from': TestShippingQuery.from_user.to_dict(),
'shipping_address': TestShippingQuery.shipping_address.to_dict()
} }
shipping_query = ShippingQuery.de_json(json_dict, bot)
def test_shippingquery_de_json(self): assert shipping_query.id == self.id
shippingquery = telegram.ShippingQuery.de_json(self.json_dict, self._bot) assert shipping_query.invoice_payload == self.invoice_payload
assert shipping_query.from_user == self.from_user
assert shipping_query.shipping_address == self.shipping_address
self.assertEqual(shippingquery.id, self._id) def test_to_dict(self, shipping_query):
self.assertEqual(shippingquery.invoice_payload, self.invoice_payload) shipping_query_dict = shipping_query.to_dict()
self.assertEqual(shippingquery.from_user, self.from_user)
self.assertEqual(shippingquery.shipping_address, self.shipping_address)
def test_shippingquery_to_json(self): assert isinstance(shipping_query_dict, dict)
shippingquery = telegram.ShippingQuery.de_json(self.json_dict, self._bot) assert shipping_query_dict['id'] == shipping_query.id
assert shipping_query_dict['invoice_payload'] == shipping_query.invoice_payload
assert shipping_query_dict['from'] == shipping_query.from_user.to_dict()
assert shipping_query_dict['shipping_address'] == shipping_query.shipping_address.to_dict()
self.assertTrue(self.is_json(shippingquery.to_json())) def test_answer(self, monkeypatch, shipping_query):
def test(*args, **kwargs):
return args[1] == shipping_query.id
def test_shippingquery_to_dict(self): monkeypatch.setattr('telegram.Bot.answer_shipping_query', test)
shippingquery = telegram.ShippingQuery.de_json(self.json_dict, self._bot).to_dict() assert shipping_query.answer()
self.assertTrue(self.is_dict(shippingquery))
self.assertDictEqual(self.json_dict, shippingquery)
def test_equality(self): def test_equality(self):
a = telegram.ShippingQuery(self._id, self.from_user, self.invoice_payload, a = ShippingQuery(self.id, self.from_user, self.invoice_payload, self.shipping_address)
self.shipping_address) b = ShippingQuery(self.id, self.from_user, self.invoice_payload, self.shipping_address)
b = telegram.ShippingQuery(self._id, self.from_user, self.invoice_payload, c = ShippingQuery(self.id, None, '', None)
self.shipping_address) d = ShippingQuery(0, self.from_user, self.invoice_payload, self.shipping_address)
c = telegram.ShippingQuery(self._id, None, '', None) e = Update(self.id)
d = telegram.ShippingQuery(0, self.from_user, self.invoice_payload, self.shipping_address)
e = telegram.Update(self._id)
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertEqual(a, c) assert a == c
self.assertEqual(hash(a), hash(c)) assert hash(a) == hash(c)
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
self.assertNotEqual(a, e) assert a != e
self.assertNotEqual(hash(a), hash(e)) assert hash(a) != hash(e)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,139 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
import pytest
from telegram import (Update, Chat, Bot, ChosenInlineResult, User, Message, CallbackQuery,
InlineQuery, ShippingQuery, PreCheckoutQuery, ShippingAddress)
from telegram.ext import ShippingQueryHandler
message = Message(1, User(1, ''), None, Chat(1, ''), text='Text')
params = [
{'message': message},
{'edited_message': message},
{'callback_query': CallbackQuery(1, User(1, ''), 'chat', message=message)},
{'channel_post': message},
{'edited_channel_post': message},
{'inline_query': InlineQuery(1, User(1, ''), '', '')},
{'chosen_inline_result': ChosenInlineResult('id', User(1, ''), '')},
{'pre_checkout_query': PreCheckoutQuery('id', User(1, ''), '', 0, '')},
{'callback_query': CallbackQuery(1, User(1, ''), 'chat')}
]
ids = ('message', 'edited_message', 'callback_query', 'channel_post',
'edited_channel_post', 'inline_query', 'chosen_inline_result',
'pre_checkout_query', 'callback_query_without_message')
@pytest.fixture(scope='class', params=params, ids=ids)
def false_update(request):
return Update(update_id=1, **request.param)
@pytest.fixture(scope='class')
def shiping_query():
return Update(1, shipping_query=ShippingQuery(42, User(1, 'test user'), 'invoice_payload',
ShippingAddress('EN', 'my_state', 'my_city',
'steer_1', '', 'post_code')))
class TestShippingQueryHandler(object):
test_flag = False
@pytest.fixture(autouse=True)
def reset(self):
self.test_flag = False
def callback_basic(self, bot, update):
test_bot = isinstance(bot, Bot)
test_update = isinstance(update, Update)
self.test_flag = test_bot and test_update
def callback_data_1(self, bot, update, user_data=None, chat_data=None):
self.test_flag = (user_data is not None) or (chat_data is not None)
def callback_data_2(self, bot, update, user_data=None, chat_data=None):
self.test_flag = (user_data is not None) and (chat_data is not None)
def callback_queue_1(self, bot, update, job_queue=None, update_queue=None):
self.test_flag = (job_queue is not None) or (update_queue is not None)
def callback_queue_2(self, bot, update, job_queue=None, update_queue=None):
self.test_flag = (job_queue is not None) and (update_queue is not None)
def test_basic(self, dp, shiping_query):
handler = ShippingQueryHandler(self.callback_basic)
dp.add_handler(handler)
assert handler.check_update(shiping_query)
dp.process_update(shiping_query)
assert self.test_flag
def test_pass_user_or_chat_data(self, dp, shiping_query):
handler = ShippingQueryHandler(self.callback_data_1, pass_user_data=True)
dp.add_handler(handler)
dp.process_update(shiping_query)
assert self.test_flag
dp.remove_handler(handler)
handler = ShippingQueryHandler(self.callback_data_1, pass_chat_data=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(shiping_query)
assert self.test_flag
dp.remove_handler(handler)
handler = ShippingQueryHandler(self.callback_data_2, pass_chat_data=True,
pass_user_data=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(shiping_query)
assert self.test_flag
def test_pass_job_or_update_queue(self, dp, shiping_query):
handler = ShippingQueryHandler(self.callback_queue_1, pass_job_queue=True)
dp.add_handler(handler)
dp.process_update(shiping_query)
assert self.test_flag
dp.remove_handler(handler)
handler = ShippingQueryHandler(self.callback_queue_1, pass_update_queue=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(shiping_query)
assert self.test_flag
dp.remove_handler(handler)
handler = ShippingQueryHandler(self.callback_queue_2, pass_job_queue=True,
pass_update_queue=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update(shiping_query)
assert self.test_flag
def test_other_update_types(self, false_update):
handler = ShippingQueryHandler(self.callback_basic)
assert not handler.check_update(false_update)

View file

@ -6,322 +6,317 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram Sticker"""
import os import os
import unittest
import pytest
from flaky import flaky from flaky import flaky
from future.utils import PY2 from future.utils import PY2
import telegram from telegram import Sticker, PhotoSize, TelegramError, StickerSet, Audio, MaskPosition
from tests.base import BaseTest, timeout from telegram.error import BadRequest
class StickerTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='function')
"""This object represents Tests for Telegram Sticker.""" def sticker_file():
f = open('tests/data/telegram.webp', 'rb')
yield f
f.close()
@classmethod
def setUpClass(cls):
super(StickerTest, cls).setUpClass()
cls.emoji = '💪' @pytest.fixture(scope='class')
# cls.sticker_file_url = "https://python-telegram-bot.org/static/testfiles/telegram.webp" def sticker(bot, chat_id):
with open('tests/data/telegram.webp', 'rb') as f:
return bot.send_sticker(chat_id, sticker=f, timeout=10).sticker
class TestSticker(object):
# sticker_file_url = 'https://python-telegram-bot.org/static/testfiles/telegram.webp'
# Serving sticker from gh since our server sends wrong content_type # Serving sticker from gh since our server sends wrong content_type
cls.sticker_file_url = "https://github.com/python-telegram-bot/python-telegram-bot/blob/master/tests/data/telegram.webp?raw=true" # noqa sticker_file_url = ('https://github.com/python-telegram-bot/python-telegram-bot/blob/master'
'/tests/data/telegram.webp?raw=true')
sticker_file = open('tests/data/telegram.webp', 'rb') emoji = '💪'
sticker = cls._bot.send_sticker(cls._chat_id, sticker=sticker_file, timeout=10).sticker width = 510
cls.sticker = sticker height = 512
cls.thumb = sticker.thumb file_size = 39518
thumb_width = 90
thumb_heigth = 90
thumb_file_size = 3672
def test_creation(self, sticker):
# Make sure file has been uploaded. # Make sure file has been uploaded.
# Simple assertions PY2 Only assert isinstance(sticker, Sticker)
assert isinstance(cls.sticker, telegram.Sticker) assert isinstance(sticker.file_id, str)
assert isinstance(cls.sticker.file_id, str) assert sticker.file_id != ''
assert cls.sticker.file_id is not '' assert isinstance(sticker.thumb, PhotoSize)
assert isinstance(cls.thumb, telegram.PhotoSize) assert isinstance(sticker.thumb.file_id, str)
assert isinstance(cls.thumb.file_id, str) assert sticker.thumb.file_id != ''
assert cls.thumb.file_id is not ''
def setUp(self): def test_expected_values(self, sticker):
self.sticker_file = open('tests/data/telegram.webp', 'rb') assert sticker.width == self.width
self.json_dict = { assert sticker.height == self.height
'file_id': self.sticker.file_id, assert sticker.file_size == self.file_size
'width': self.sticker.width, assert sticker.thumb.width == self.thumb_width
'height': self.sticker.height, assert sticker.thumb.height == self.thumb_heigth
'thumb': self.thumb.to_dict(), assert sticker.thumb.file_size == self.thumb_file_size
'emoji': self.emoji,
'file_size': self.sticker.file_size
}
def test_expected_values(self):
self.assertEqual(self.sticker.width, 510)
self.assertEqual(self.sticker.height, 512)
self.assertEqual(self.sticker.file_size, 39518)
self.assertEqual(self.thumb.width, 90)
self.assertEqual(self.thumb.height, 90)
self.assertEqual(self.thumb.file_size, 3672)
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_send_sticker_all_args(self): def test_send_all_args(self, bot, chat_id, sticker_file, sticker):
message = self._bot.sendSticker(chat_id=self._chat_id, sticker=self.sticker.file_id, disable_notification=False) message = bot.send_sticker(chat_id, sticker=sticker_file, disable_notification=False)
sticker = message.sticker
self.assertEqual(sticker, self.sticker) assert isinstance(message.sticker, Sticker)
assert isinstance(message.sticker.file_id, str)
assert message.sticker.file_id != ''
assert message.sticker.width == sticker.width
assert message.sticker.height == sticker.height
assert message.sticker.file_size == sticker.file_size
assert isinstance(message.sticker.thumb, PhotoSize)
assert isinstance(message.sticker.thumb.file_id, str)
assert message.sticker.thumb.file_id != ''
assert message.sticker.thumb.width == sticker.thumb.width
assert message.sticker.thumb.height == sticker.thumb.height
assert message.sticker.thumb.file_size == sticker.thumb.file_size
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_get_and_download_sticker(self): def test_get_and_download(self, bot, sticker):
new_file = self._bot.getFile(self.sticker.file_id) new_file = bot.get_file(sticker.file_id)
self.assertEqual(new_file.file_size, self.sticker.file_size) assert new_file.file_size == sticker.file_size
self.assertEqual(new_file.file_id, self.sticker.file_id) assert new_file.file_id == sticker.file_id
self.assertTrue(new_file.file_path.startswith('https://')) assert new_file.file_path.startswith('https://')
new_file.download('telegram.webp') new_file.download('telegram.webp')
self.assertTrue(os.path.isfile('telegram.webp')) assert os.path.isfile('telegram.webp')
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_send_sticker_resend(self): def test_resend(self, bot, chat_id, sticker):
message = self._bot.sendSticker(chat_id=self._chat_id, sticker=self.sticker.file_id) message = bot.send_sticker(chat_id=chat_id, sticker=sticker.file_id)
sticker = message.sticker assert message.sticker == sticker
self.assertEqual(sticker.file_id, self.sticker.file_id)
self.assertEqual(sticker.width, self.sticker.width)
self.assertEqual(sticker.height, self.sticker.height)
self.assertIsInstance(sticker.thumb, telegram.PhotoSize)
self.assertEqual(sticker.file_size, self.sticker.file_size)
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_sticker_on_server_emoji(self): def test_send_on_server_emoji(self, bot, chat_id):
server_file_id = "CAADAQADHAADyIsGAAFZfq1bphjqlgI" server_file_id = 'CAADAQADHAADyIsGAAFZfq1bphjqlgI'
message = self._bot.sendSticker(chat_id=self._chat_id, sticker=server_file_id) message = bot.send_sticker(chat_id=chat_id, sticker=server_file_id)
sticker = message.sticker sticker = message.sticker
if PY2: if PY2:
self.assertEqual(sticker.emoji, self.emoji.decode('utf-8')) assert sticker.emoji == self.emoji.decode('utf-8')
else: else:
self.assertEqual(sticker.emoji, self.emoji) assert sticker.emoji == self.emoji
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_send_sticker_from_url(self): def test_send_from_url(self, bot, chat_id):
message = self._bot.sendSticker(chat_id=self._chat_id, sticker=self.sticker_file_url) message = bot.send_sticker(chat_id=chat_id, sticker=self.sticker_file_url)
sticker = message.sticker sticker = message.sticker
self.assertIsInstance(sticker, telegram.Sticker) assert isinstance(message.sticker, Sticker)
self.assertIsInstance(sticker.file_id, str) assert isinstance(message.sticker.file_id, str)
self.assertNotEqual(sticker.file_id, '') assert message.sticker.file_id != ''
self.assertEqual(sticker.file_size, self.sticker.file_size) assert message.sticker.width == sticker.width
self.assertEqual(sticker.height, self.sticker.height) assert message.sticker.height == sticker.height
self.assertEqual(sticker.width, self.sticker.width) assert message.sticker.file_size == sticker.file_size
thumb = sticker.thumb
self.assertIsInstance(thumb, telegram.PhotoSize)
self.assertIsInstance(thumb.file_id, str)
self.assertNotEqual(thumb.file_id, '')
self.assertEqual(thumb.file_size, self.thumb.file_size)
self.assertEqual(thumb.width, self.thumb.width)
self.assertEqual(thumb.height, self.thumb.height)
def test_sticker_de_json(self): assert isinstance(message.sticker.thumb, PhotoSize)
sticker = telegram.Sticker.de_json(self.json_dict, self._bot) assert isinstance(message.sticker.thumb.file_id, str)
assert message.sticker.thumb.file_id != ''
assert message.sticker.thumb.width == sticker.thumb.width
assert message.sticker.thumb.height == sticker.thumb.height
assert message.sticker.thumb.file_size == sticker.thumb.file_size
self.assertEqual(sticker.file_id, self.sticker.file_id) def test_de_json(self, bot, sticker):
self.assertEqual(sticker.width, self.sticker.width) json_dict = {
self.assertEqual(sticker.height, self.sticker.height) 'file_id': 'not a file id',
self.assertIsInstance(sticker.thumb, telegram.PhotoSize) 'width': self.width,
self.assertEqual(sticker.emoji, self.emoji) 'height': self.height,
self.assertEqual(sticker.file_size, self.sticker.file_size) 'thumb': sticker.thumb.to_dict(),
'emoji': self.emoji,
'file_size': self.file_size
}
json_sticker = Sticker.de_json(json_dict, bot)
assert json_sticker.file_id == 'not a file id'
assert json_sticker.width == self.width
assert json_sticker.height == self.height
assert json_sticker.emoji == self.emoji
assert json_sticker.file_size == self.file_size
assert json_sticker.thumb == sticker.thumb
def test_send_with_sticker(self, monkeypatch, bot, chat_id, sticker):
def test(_, url, data, **kwargs):
return data['sticker'] == sticker.file_id
monkeypatch.setattr('telegram.utils.request.Request.post', test)
message = bot.send_sticker(sticker=sticker, chat_id=chat_id)
assert message
def test_to_dict(self, sticker):
sticker_dict = sticker.to_dict()
assert isinstance(sticker_dict, dict)
assert sticker_dict['file_id'] == sticker.file_id
assert sticker_dict['width'] == sticker.width
assert sticker_dict['height'] == sticker.height
assert sticker_dict['file_size'] == sticker.file_size
assert sticker_dict['thumb'] == sticker.thumb.to_dict()
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_send_sticker_with_sticker(self): def test_error_send_empty_file(self, bot, chat_id):
message = self._bot.send_sticker(sticker=self.sticker, chat_id=self._chat_id) with pytest.raises(TelegramError):
sticker = message.sticker bot.send_sticker(chat_id, open(os.devnull, 'rb'))
self.assertEqual(sticker, self.sticker)
def test_sticker_to_json(self):
self.assertTrue(self.is_json(self.sticker.to_json()))
def test_sticker_to_dict(self):
sticker = self.sticker.to_dict()
self.is_dict(sticker)
self.assertEqual(sticker['file_id'], self.sticker.file_id)
self.assertEqual(sticker['width'], self.sticker.width)
self.assertEqual(sticker['height'], self.sticker.height)
self.assertIsInstance(sticker['thumb'], dict)
self.assertEqual(sticker['file_size'], self.sticker.file_size)
@flaky(3, 1) @flaky(3, 1)
@timeout(10) @pytest.mark.timeout(10)
def test_error_send_sticker_empty_file(self): def test_error_send_empty_file_id(self, bot, chat_id):
json_dict = self.json_dict with pytest.raises(TelegramError):
bot.send_sticker(chat_id, '')
del (json_dict['file_id']) def test_error_without_required_args(self, bot, chat_id):
json_dict['sticker'] = open(os.devnull, 'rb') with pytest.raises(TypeError):
bot.send_sticker(chat_id)
with self.assertRaises(telegram.TelegramError): def test_equality(self, sticker):
self._bot.sendSticker(chat_id=self._chat_id, **json_dict) a = Sticker(sticker.file_id, self.width, self.height)
b = Sticker(sticker.file_id, self.width, self.height)
c = Sticker(sticker.file_id, 0, 0)
d = Sticker('', self.width, self.height)
e = PhotoSize(sticker.file_id, self.width, self.height)
@flaky(3, 1) assert a == b
@timeout(10) assert hash(a) == hash(b)
def test_error_send_sticker_empty_file_id(self): assert a is not b
json_dict = self.json_dict
del (json_dict['file_id']) assert a == c
json_dict['sticker'] = '' assert hash(a) == hash(c)
with self.assertRaises(telegram.TelegramError): assert a != d
self._bot.sendSticker(chat_id=self._chat_id, **json_dict) assert hash(a) != hash(d)
@flaky(3, 1) assert a != e
@timeout(10) assert hash(a) != hash(e)
def test_error_sticker_without_required_args(self):
json_dict = self.json_dict
del (json_dict['file_id'])
with self.assertRaises(TypeError):
self._bot.sendSticker(chat_id=self._chat_id, **json_dict)
@flaky(3, 1)
@timeout(10)
def test_reply_sticker(self):
"""Test for Message.reply_sticker"""
message = self._bot.sendMessage(self._chat_id, '.')
message = message.reply_sticker(self.sticker.file_id)
self.assertNotEqual(message.sticker.file_id, '')
def test_equality(self):
a = telegram.Sticker(self.sticker.file_id, self.sticker.width, self.sticker.height)
b = telegram.Sticker(self.sticker.file_id, self.sticker.width, self.sticker.height)
c = telegram.Sticker(self.sticker.file_id, 0, 0)
d = telegram.Sticker("", self.sticker.width, self.sticker.height)
e = telegram.PhotoSize(self.sticker.file_id, self.sticker.width, self.sticker.height)
self.assertEqual(a, b)
self.assertEqual(hash(a), hash(b))
self.assertIsNot(a, b)
self.assertEqual(a, c)
self.assertEqual(hash(a), hash(c))
self.assertNotEqual(a, d)
self.assertNotEqual(hash(a), hash(d))
self.assertNotEqual(a, e)
self.assertNotEqual(hash(a), hash(e))
class TestStickerSet(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
# TODO: Implement bot tests for StickerSet def sticker_set(bot):
# It's hard to test creation when we can't delete sticker sets return bot.get_sticker_set('test_by_{0}'.format(bot.username))
def setUp(self):
self.name = 'test_by_{0}'.format(self._bot.username)
self.title = 'Test stickers'
self.contains_masks = False
self.stickers = [telegram.Sticker('file_id', 512, 512)]
self.json_dict = {
'name': self.name, class TestStickerSet(object):
title = 'Test stickers'
contains_masks = False
stickers = [Sticker('file_id', 512, 512)]
name = 'NOTAREALNAME'
def test_de_json(self, bot):
name = 'test_by_{0}'.format(bot.username)
json_dict = {
'name': name,
'title': self.title, 'title': self.title,
'contains_masks': self.contains_masks, 'contains_masks': self.contains_masks,
'stickers': [x.to_dict() for x in self.stickers] 'stickers': [x.to_dict() for x in self.stickers]
} }
sticker_set = StickerSet.de_json(json_dict, bot)
def test_sticker_set_de_json(self): assert sticker_set.name == name
sticker_set = telegram.StickerSet.de_json(self.json_dict, self._bot) assert sticker_set.title == self.title
assert sticker_set.contains_masks == self.contains_masks
assert sticker_set.stickers == self.stickers
self.assertEqual(sticker_set.name, self.name) def test_sticker_set_to_dict(self, sticker_set):
self.assertEqual(sticker_set.title, self.title) sticker_set_dict = sticker_set.to_dict()
self.assertEqual(sticker_set.contains_masks, self.contains_masks)
self.assertEqual(sticker_set.stickers, self.stickers)
def test_sticker_set_to_json(self): assert isinstance(sticker_set_dict, dict)
sticker_set = telegram.StickerSet.de_json(self.json_dict, self._bot) assert sticker_set_dict['name'] == sticker_set.name
assert sticker_set_dict['title'] == sticker_set.title
assert sticker_set_dict['contains_masks'] == sticker_set.contains_masks
assert sticker_set_dict['stickers'][0] == sticker_set.stickers[0].to_dict()
self.assertTrue(self.is_json(sticker_set.to_json())) def test_bot_methods_1(self, bot, sticker_set):
with open('tests/data/telegram_sticker.png', 'rb') as f:
file = bot.upload_sticker_file(95205500, f)
assert file
assert bot.add_sticker_to_set(95205500, sticker_set.name, file.file_id, '😄')
def test_sticker_set_to_dict(self): @pytest.mark.xfail(raises=BadRequest, reason='STICKERSET_NOT_MODIFIED errors on deletion')
sticker_set = telegram.StickerSet.de_json(self.json_dict, self._bot).to_dict() def test_bot_methods_2(self, bot, sticker_set):
updated_sticker_set = bot.get_sticker_set(sticker_set.name)
self.assertTrue(self.is_dict(sticker_set)) assert len(updated_sticker_set.stickers) > 1 # Otherwise test_bot_methods_1 failed
self.assertDictEqual(self.json_dict, sticker_set) file_id = updated_sticker_set.stickers[-1].file_id
assert bot.set_sticker_position_in_set(file_id, len(updated_sticker_set.stickers) - 1)
assert bot.delete_sticker_from_set(file_id)
def test_equality(self): def test_equality(self):
a = telegram.StickerSet(self.name, self.title, self.contains_masks, self.stickers) a = StickerSet(self.name, self.title, self.contains_masks, self.stickers)
b = telegram.StickerSet(self.name, self.title, self.contains_masks, self.stickers) b = StickerSet(self.name, self.title, self.contains_masks, self.stickers)
c = telegram.StickerSet(self.name, None, None, None) c = StickerSet(self.name, None, None, None)
d = telegram.StickerSet('blah', self.title, self.contains_masks, self.stickers) d = StickerSet('blah', self.title, self.contains_masks, self.stickers)
e = telegram.Audio(self.name, 0, None, None) e = Audio(self.name, 0, None, None)
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertEqual(a, c) assert a == c
self.assertEqual(hash(a), hash(c)) assert hash(a) == hash(c)
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
self.assertNotEqual(a, e) assert a != e
self.assertNotEqual(hash(a), hash(e)) assert hash(a) != hash(e)
class TestMaskPosition(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
def setUp(self): def mask_position():
self.point = telegram.MaskPosition.EYES return MaskPosition(TestMaskPosition.point,
self.x_shift = -1 TestMaskPosition.x_shift,
self.y_shift = 1 TestMaskPosition.y_shift,
self.scale = 2 TestMaskPosition.scale)
self.json_dict = {
class TestMaskPosition(object):
point = MaskPosition.EYES
x_shift = -1
y_shift = 1
scale = 2
def test_mask_position_de_json(self, bot):
json_dict = {
'point': self.point, 'point': self.point,
'x_shift': self.x_shift, 'x_shift': self.x_shift,
'y_shift': self.y_shift, 'y_shift': self.y_shift,
'scale': self.scale 'scale': self.scale
} }
mask_position = MaskPosition.de_json(json_dict, bot)
def test_mask_position_de_json(self): assert mask_position.point == self.point
mask_position = telegram.MaskPosition.de_json(self.json_dict, self._bot) assert mask_position.x_shift == self.x_shift
assert mask_position.y_shift == self.y_shift
assert mask_position.scale == self.scale
self.assertEqual(mask_position.point, self.point) def test_mask_position_to_dict(self, mask_position):
self.assertEqual(mask_position.x_shift, self.x_shift) mask_position_dict = mask_position.to_dict()
self.assertEqual(mask_position.y_shift, self.y_shift)
self.assertEqual(mask_position.scale, self.scale)
def test_mask_positiont_to_json(self): assert isinstance(mask_position_dict, dict)
mask_position = telegram.MaskPosition.de_json(self.json_dict, self._bot) assert mask_position_dict['point'] == mask_position.point
assert mask_position_dict['x_shift'] == mask_position.x_shift
self.assertTrue(self.is_json(mask_position.to_json())) assert mask_position_dict['y_shift'] == mask_position.y_shift
assert mask_position_dict['scale'] == mask_position.scale
def test_mask_position_to_dict(self):
mask_position = telegram.MaskPosition.de_json(self.json_dict, self._bot).to_dict()
self.assertTrue(self.is_dict(mask_position))
self.assertDictEqual(self.json_dict, mask_position)
if __name__ == '__main__':
unittest.main()

View file

@ -0,0 +1,123 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
import pytest
from telegram import (Bot, Update, Message, User, Chat, CallbackQuery, InlineQuery,
ChosenInlineResult, ShippingQuery, PreCheckoutQuery)
from telegram.ext import StringCommandHandler
message = Message(1, User(1, ''), None, Chat(1, ''), text='Text')
params = [
{'message': message},
{'edited_message': message},
{'callback_query': CallbackQuery(1, User(1, ''), 'chat', message=message)},
{'channel_post': message},
{'edited_channel_post': message},
{'inline_query': InlineQuery(1, User(1, ''), '', '')},
{'chosen_inline_result': ChosenInlineResult('id', User(1, ''), '')},
{'shipping_query': ShippingQuery('id', User(1, ''), '', None)},
{'pre_checkout_query': PreCheckoutQuery('id', User(1, ''), '', 0, '')},
{'callback_query': CallbackQuery(1, User(1, ''), 'chat')}
]
ids = ('message', 'edited_message', 'callback_query', 'channel_post',
'edited_channel_post', 'inline_query', 'chosen_inline_result',
'shipping_query', 'pre_checkout_query', 'callback_query_without_message')
@pytest.fixture(scope='class', params=params, ids=ids)
def false_update(request):
return Update(update_id=1, **request.param)
class TestStringCommandHandler(object):
test_flag = False
@pytest.fixture(autouse=True)
def reset(self):
self.test_flag = False
def callback_basic(self, bot, update):
test_bot = isinstance(bot, Bot)
test_update = isinstance(update, str)
self.test_flag = test_bot and test_update
def callback_queue_1(self, bot, update, job_queue=None, update_queue=None):
self.test_flag = (job_queue is not None) or (update_queue is not None)
def callback_queue_2(self, bot, update, job_queue=None, update_queue=None):
self.test_flag = (job_queue is not None) and (update_queue is not None)
def sch_callback_args(self, bot, update, args):
if update == '/test':
self.test_flag = len(args) == 0
else:
self.test_flag = args == ['one', 'two']
def test_basic(self, dp):
handler = StringCommandHandler('test', self.callback_basic)
dp.add_handler(handler)
assert handler.check_update('/test')
dp.process_update('/test')
assert self.test_flag
assert not handler.check_update('/nottest')
assert not handler.check_update('not /test in front')
assert handler.check_update('/test followed by text')
def test_pass_args(self, dp):
handler = StringCommandHandler('test', self.sch_callback_args, pass_args=True)
dp.add_handler(handler)
dp.process_update('/test')
assert self.test_flag
self.test_flag = False
dp.process_update('/test one two')
assert self.test_flag
def test_pass_job_or_update_queue(self, dp):
handler = StringCommandHandler('test', self.callback_queue_1, pass_job_queue=True)
dp.add_handler(handler)
dp.process_update('/test')
assert self.test_flag
dp.remove_handler(handler)
handler = StringCommandHandler('test', self.callback_queue_1, pass_update_queue=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update('/test')
assert self.test_flag
dp.remove_handler(handler)
handler = StringCommandHandler('test', self.callback_queue_2, pass_job_queue=True,
pass_update_queue=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update('/test')
assert self.test_flag
def test_other_update_types(self, false_update):
handler = StringCommandHandler('test', self.callback_basic)
assert not handler.check_update(false_update)

View file

@ -0,0 +1,127 @@
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2017
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser 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 Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
import pytest
from telegram import (Bot, Update, Message, User, Chat, CallbackQuery, InlineQuery,
ChosenInlineResult, ShippingQuery, PreCheckoutQuery)
from telegram.ext import StringRegexHandler
message = Message(1, User(1, ''), None, Chat(1, ''), text='Text')
params = [
{'message': message},
{'edited_message': message},
{'callback_query': CallbackQuery(1, User(1, ''), 'chat', message=message)},
{'channel_post': message},
{'edited_channel_post': message},
{'inline_query': InlineQuery(1, User(1, ''), '', '')},
{'chosen_inline_result': ChosenInlineResult('id', User(1, ''), '')},
{'shipping_query': ShippingQuery('id', User(1, ''), '', None)},
{'pre_checkout_query': PreCheckoutQuery('id', User(1, ''), '', 0, '')},
{'callback_query': CallbackQuery(1, User(1, ''), 'chat')}
]
ids = ('message', 'edited_message', 'callback_query', 'channel_post',
'edited_channel_post', 'inline_query', 'chosen_inline_result',
'shipping_query', 'pre_checkout_query', 'callback_query_without_message')
@pytest.fixture(scope='class', params=params, ids=ids)
def false_update(request):
return Update(update_id=1, **request.param)
class TestStringRegexHandler(object):
test_flag = False
@pytest.fixture(autouse=True)
def reset(self):
self.test_flag = False
def callback_basic(self, bot, update):
test_bot = isinstance(bot, Bot)
test_update = isinstance(update, str)
self.test_flag = test_bot and test_update
def callback_queue_1(self, bot, update, job_queue=None, update_queue=None):
self.test_flag = (job_queue is not None) or (update_queue is not None)
def callback_queue_2(self, bot, update, job_queue=None, update_queue=None):
self.test_flag = (job_queue is not None) and (update_queue is not None)
def callback_group(self, bot, update, groups=None, groupdict=None):
if groups is not None:
self.test_flag = groups == ('t', ' message')
if groupdict is not None:
self.test_flag = groupdict == {'begin': 't', 'end': ' message'}
def test_basic(self, dp):
handler = StringRegexHandler('(?P<begin>.*)est(?P<end>.*)', self.callback_basic)
dp.add_handler(handler)
assert handler.check_update('test message')
dp.process_update('test message')
assert self.test_flag
assert not handler.check_update('does not match')
def test_with_passing_group_dict(self, dp):
handler = StringRegexHandler('(?P<begin>.*)est(?P<end>.*)', self.callback_group,
pass_groups=True)
dp.add_handler(handler)
dp.process_update('test message')
assert self.test_flag
dp.remove_handler(handler)
handler = StringRegexHandler('(?P<begin>.*)est(?P<end>.*)', self.callback_group,
pass_groupdict=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update('test message')
assert self.test_flag
def test_pass_job_or_update_queue(self, dp):
handler = StringRegexHandler('test', self.callback_queue_1, pass_job_queue=True)
dp.add_handler(handler)
dp.process_update('test')
assert self.test_flag
dp.remove_handler(handler)
handler = StringRegexHandler('test', self.callback_queue_1, pass_update_queue=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update('test')
assert self.test_flag
dp.remove_handler(handler)
handler = StringRegexHandler('test', self.callback_queue_2, pass_job_queue=True,
pass_update_queue=True)
dp.add_handler(handler)
self.test_flag = False
dp.process_update('test')
assert self.test_flag
def test_other_update_types(self, false_update):
handler = StringRegexHandler('test', self.callback_basic)
assert not handler.check_update(false_update)

View file

@ -5,42 +5,45 @@
# Leandro Toledo de Souza <devs@python-telegram-bot.org> # Leandro Toledo de Souza <devs@python-telegram-bot.org>
# #
# This program is free software: you can redistribute it and/or modify # This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by # it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version. # (at your option) any later version.
# #
# This program is distributed in the hope that it will be useful, # This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. # GNU Lesser Public License for more details.
# #
# You should have received a copy of the GNU General Public License # You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/]. # along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module contains an object that represents Tests for Telegram
SuccessfulPayment"""
import sys import pytest
import unittest
sys.path.append('.') from telegram import OrderInfo, SuccessfulPayment
import telegram
from tests.base import BaseTest
class SuccessfulPaymentTest(BaseTest, unittest.TestCase): @pytest.fixture(scope='class')
"""This object represents Tests for Telegram SuccessfulPayment.""" def successful_payment():
return SuccessfulPayment(TestSuccessfulPayment.currency,
TestSuccessfulPayment.total_amount,
TestSuccessfulPayment.invoice_payload,
TestSuccessfulPayment.telegram_payment_charge_id,
TestSuccessfulPayment.provider_payment_charge_id,
shipping_option_id=TestSuccessfulPayment.shipping_option_id,
order_info=TestSuccessfulPayment.order_info)
def setUp(self):
self.invoice_payload = 'invoice_payload'
self.shipping_option_id = 'shipping_option_id'
self.currency = 'EUR'
self.total_amount = 100
self.order_info = telegram.OrderInfo()
self.telegram_payment_charge_id = 'telegram_payment_charge_id'
self.provider_payment_charge_id = 'provider_payment_charge_id'
self.json_dict = { class TestSuccessfulPayment(object):
invoice_payload = 'invoice_payload'
shipping_option_id = 'shipping_option_id'
currency = 'EUR'
total_amount = 100
order_info = OrderInfo()
telegram_payment_charge_id = 'telegram_payment_charge_id'
provider_payment_charge_id = 'provider_payment_charge_id'
def test_de_json(self, bot):
json_dict = {
'invoice_payload': self.invoice_payload, 'invoice_payload': self.invoice_payload,
'shipping_option_id': self.shipping_option_id, 'shipping_option_id': self.shipping_option_id,
'currency': self.currency, 'currency': self.currency,
@ -49,52 +52,47 @@ class SuccessfulPaymentTest(BaseTest, unittest.TestCase):
'telegram_payment_charge_id': self.telegram_payment_charge_id, 'telegram_payment_charge_id': self.telegram_payment_charge_id,
'provider_payment_charge_id': self.provider_payment_charge_id 'provider_payment_charge_id': self.provider_payment_charge_id
} }
successful_payment = SuccessfulPayment.de_json(json_dict, bot)
def test_successfulpayment_de_json(self): assert successful_payment.invoice_payload == self.invoice_payload
successfulpayment = telegram.SuccessfulPayment.de_json(self.json_dict, self._bot) assert successful_payment.shipping_option_id == self.shipping_option_id
assert successful_payment.currency == self.currency
assert successful_payment.order_info == self.order_info
assert successful_payment.telegram_payment_charge_id == self.telegram_payment_charge_id
assert successful_payment.provider_payment_charge_id == self.provider_payment_charge_id
self.assertEqual(successfulpayment.invoice_payload, self.invoice_payload) def test_to_dict(self, successful_payment):
self.assertEqual(successfulpayment.shipping_option_id, self.shipping_option_id) successful_payment_dict = successful_payment.to_dict()
self.assertEqual(successfulpayment.currency, self.currency)
self.assertEqual(successfulpayment.order_info, self.order_info)
self.assertEqual(successfulpayment.telegram_payment_charge_id,
self.telegram_payment_charge_id)
self.assertEqual(successfulpayment.provider_payment_charge_id,
self.provider_payment_charge_id)
def test_successfulpayment_to_json(self): assert isinstance(successful_payment_dict, dict)
successfulpayment = telegram.SuccessfulPayment.de_json(self.json_dict, self._bot) assert successful_payment_dict['invoice_payload'] == successful_payment.invoice_payload
assert successful_payment_dict['shipping_option_id'] == \
self.assertTrue(self.is_json(successfulpayment.to_json())) successful_payment.shipping_option_id
assert successful_payment_dict['currency'] == successful_payment.currency
def test_successfulpayment_to_dict(self): assert successful_payment_dict['order_info'] == successful_payment.order_info.to_dict()
successfulpayment = telegram.SuccessfulPayment.de_json(self.json_dict, self._bot).to_dict() assert successful_payment_dict['telegram_payment_charge_id'] == \
successful_payment.telegram_payment_charge_id
self.assertTrue(self.is_dict(successfulpayment)) assert successful_payment_dict['provider_payment_charge_id'] == \
self.assertDictEqual(self.json_dict, successfulpayment) successful_payment.provider_payment_charge_id
def test_equality(self): def test_equality(self):
a = telegram.SuccessfulPayment(self.currency, self.total_amount, self.invoice_payload, a = SuccessfulPayment(self.currency, self.total_amount, self.invoice_payload,
self.telegram_payment_charge_id, self.telegram_payment_charge_id,
self.provider_payment_charge_id) self.provider_payment_charge_id)
b = telegram.SuccessfulPayment(self.currency, self.total_amount, self.invoice_payload, b = SuccessfulPayment(self.currency, self.total_amount, self.invoice_payload,
self.telegram_payment_charge_id, self.telegram_payment_charge_id,
self.provider_payment_charge_id) self.provider_payment_charge_id)
c = telegram.SuccessfulPayment('', 0, '', self.telegram_payment_charge_id, c = SuccessfulPayment('', 0, '', self.telegram_payment_charge_id,
self.provider_payment_charge_id) self.provider_payment_charge_id)
d = telegram.SuccessfulPayment(self.currency, self.total_amount, self.invoice_payload, d = SuccessfulPayment(self.currency, self.total_amount, self.invoice_payload,
self.telegram_payment_charge_id, '') self.telegram_payment_charge_id, '')
self.assertEqual(a, b) assert a == b
self.assertEqual(hash(a), hash(b)) assert hash(a) == hash(b)
self.assertIsNot(a, b) assert a is not b
self.assertEqual(a, c) assert a == c
self.assertEqual(hash(a), hash(c)) assert hash(a) == hash(c)
self.assertNotEqual(a, d) assert a != d
self.assertNotEqual(hash(a), hash(d)) assert hash(a) != hash(d)
if __name__ == '__main__':
unittest.main()

Some files were not shown because too many files have changed in this diff Show more