Skip to content

Commit

Permalink
Merge e193e5b into 1bff367
Browse files Browse the repository at this point in the history
  • Loading branch information
Y0hy0h committed Apr 15, 2017
2 parents 1bff367 + e193e5b commit 01bdd34
Show file tree
Hide file tree
Showing 22 changed files with 125 additions and 117 deletions.
2 changes: 1 addition & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
templates_path = ['_templates']

intersphinx_mapping = {'telegram': ('http://python-telegram-bot.readthedocs.io/en/latest/', None)}
# The suffix(es) of source filenames.
# The suffix(es) of source file names.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
Expand Down
5 changes: 3 additions & 2 deletions examples/test_conversationbot2.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import absolute_import

import unittest

from ptbtest import UserGenerator
from telegram import ReplyKeyboardMarkup
from telegram.ext import CommandHandler
from telegram.ext import ConversationHandler
Expand All @@ -13,6 +13,7 @@
from ptbtest import ChatGenerator
from ptbtest import MessageGenerator
from ptbtest import Mockbot
from ptbtest import UserGenerator

"""
This is an example to show how the ptbtest suite can be used.
Expand Down Expand Up @@ -112,7 +113,7 @@ def done(bot, update, user_data):
self.updater.start_polling()

# We are going to test a conversationhandler. Since this is tied in with user and chat we need to
# create both for consistancy
# create both for consistency
user = self.ug.get_user()
chat = self.cg.get_chat(type="group")
user2 = self.ug.get_user()
Expand Down
13 changes: 8 additions & 5 deletions examples/test_echobot2.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from __future__ import absolute_import

import unittest

from telegram.ext import CommandHandler
Expand All @@ -17,6 +18,8 @@
https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/echobot2.py
"""


class TestEchobot2(unittest.TestCase):
def setUp(self):
# For use within the tests we nee some stuff. Starting with a Mockbot
Expand All @@ -28,6 +31,10 @@ def setUp(self):
self.mg = MessageGenerator(self.bot)
self.updater = Updater(bot=self.bot)

def tearDown(self):
# Always stop the updater at the end of a test case so it won't hang.
self.updater.stop()

def test_help(self):
# this tests the help handler. So first insert the handler
def help(bot, update):
Expand All @@ -36,7 +43,7 @@ def help(bot, update):
# Then register the handler with he updater's dispatcher and start polling
self.updater.dispatcher.add_handler(CommandHandler("help", help))
self.updater.start_polling()
# We want to simulate a message. Since we don't care wich user sends it we let the MessageGenerator
# We want to simulate a message. Since we don't care which user sends it we let the MessageGenerator
# create random ones
update = self.mg.get_message(text="/help")
# We insert the update with the bot so the updater can retrieve it.
Expand All @@ -47,8 +54,6 @@ def help(bot, update):
sent = self.bot.sent_messages[0]
self.assertEqual(sent['method'], "sendMessage")
self.assertEqual(sent['text'], "Help!")
# Always stop the updater at the end of a testcase so it won't hang.
self.updater.stop()

def test_start(self):
def start(bot, update):
Expand All @@ -65,7 +70,6 @@ def start(bot, update):
sent = self.bot.sent_messages[0]
self.assertEqual(sent['method'], "sendMessage")
self.assertEqual(sent['text'], "Hi!")
self.updater.stop()

def test_echo(self):
def echo(bot, update):
Expand All @@ -82,7 +86,6 @@ def echo(bot, update):
self.assertEqual(sent[0]['method'], "sendMessage")
self.assertEqual(sent[0]['text'], "first message")
self.assertEqual(sent[1]['text'], "second message")
self.updater.stop()


if __name__ == '__main__':
Expand Down
8 changes: 6 additions & 2 deletions examples/test_inlinekeyboard.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
from __future__ import absolute_import

import unittest

from ptbtest import CallbackQueryGenerator
from telegram import InlineKeyboardButton
from telegram import InlineKeyboardMarkup
from telegram.ext import CallbackQueryHandler
from telegram.ext import Updater

from ptbtest import CallbackQueryGenerator
from ptbtest import ChatGenerator
from ptbtest import MessageGenerator
from ptbtest import Mockbot
Expand All @@ -18,6 +19,8 @@
We will skip the start and help callbacks and focus on the callback query.
"""


class TestInlineKeyboard(unittest.TestCase):
def setUp(self):
# For use within the tests we nee some stuff. Starting with a Mockbot
Expand All @@ -37,11 +40,12 @@ def button(bot, update):
bot.editMessageText(text="Selected option: %s" % query.data,
chat_id=query.message.chat_id,
message_id=query.message.message_id)

dp = self.updater.dispatcher
dp.add_handler(CallbackQueryHandler(button))
self.updater.start_polling()

# the start callback in this example generates a message that will be edited, so let's mimick that message
# the start callback in this example generates a message that will be edited, so let's mimic that message
# for future reference
keyboard = [[InlineKeyboardButton("Option 1", callback_data='1'),
InlineKeyboardButton("Option 2", callback_data='2')],
Expand Down
7 changes: 5 additions & 2 deletions examples/test_timerbot.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import absolute_import
import unittest

import time
import unittest

from telegram.ext import CommandHandler
from telegram.ext import Job
Expand All @@ -18,6 +18,8 @@
We will skip the start and help handlers and focus on the timer.
"""


class Testtimerbot(unittest.TestCase):
def setUp(self):
# For use within the tests we nee some stuff. Starting with a Mockbot
Expand Down Expand Up @@ -66,6 +68,7 @@ def unset(bot, update, chat_data):
del chat_data['job']

update.message.reply_text('Timer successfully unset!')

# Now add those handlers to the updater and start polling
dp = self.updater.dispatcher
dp.add_handler(CommandHandler("set", set,
Expand Down Expand Up @@ -122,4 +125,4 @@ def unset(bot, update, chat_data):


if __name__ == '__main__':
unittest.main()
unittest.main()
14 changes: 8 additions & 6 deletions ptbtest/callbackquerygenerator.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# pylint: disable=E0611,E0213,E1102,C0103,E1101,W0613,R0913,R0904
#
# A library that provides a testing suite fot python-telegram-bot
# wich can be found on https://github.com/python-telegram-bot/python-telegram-bot
# which can be found on https://github.com/python-telegram-bot/python-telegram-bot
# Copyright (C) 2017
# Pieter Schutz - https://github.com/eldinnie
#
Expand All @@ -21,12 +21,13 @@
"""This module provides a class to generate telegram callback queries"""
import uuid

from .updategenerator import update
from .ptbgenerator import PtbGenerator
from telegram import (CallbackQuery, Message, User)

from ptbtest import (ChatGenerator, MessageGenerator, Mockbot, UserGenerator)
from ptbtest.errors import (BadBotException, BadCallbackQueryException,
BadMessageException, BadUserException)
from telegram import (CallbackQuery, Message, User)
from .ptbgenerator import PtbGenerator
from .updategenerator import update


class CallbackQueryGenerator(PtbGenerator):
Expand All @@ -37,7 +38,7 @@ class CallbackQueryGenerator(PtbGenerator):
bot (ptbtest.Mockbot): Bot to encode with the messages
Args:
bot (Optional[ptbtest.Mockbot]): supply your own for a custom botname
bot (Optional[ptbtest.Mockbot]): supply your own for a custom bot name
"""

def __init__(self, bot=None):
Expand Down Expand Up @@ -118,5 +119,6 @@ def get_callback_query(self,
data, inline_message_id, game_short_name,
self.bot)

def _gen_id(self):
@staticmethod
def _gen_id():
return str(uuid.uuid4())
7 changes: 4 additions & 3 deletions ptbtest/chatgenerator.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# pylint: disable=E0611,E0213,E1102,C0103,E1101,W0613,R0913,R0904
#
# A library that provides a testing suite fot python-telegram-bot
# wich can be found on https://github.com/python-telegram-bot/python-telegram-bot
# which can be found on https://github.com/python-telegram-bot/python-telegram-bot
# Copyright (C) 2017
# Pieter Schutz - https://github.com/eldinnie
#
Expand All @@ -21,10 +21,11 @@
"""This module provides a class to generate telegram chats"""
import random

from .ptbgenerator import PtbGenerator
from ptbtest import UserGenerator
from telegram import (Chat, User)

from ptbtest import UserGenerator
from .ptbgenerator import PtbGenerator


class ChatGenerator(PtbGenerator):
"""
Expand Down
47 changes: 25 additions & 22 deletions ptbtest/entityparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# pylint: disable=E0611,E0213,E1102,C0103,E1101,W0613,R0913,R0904
#
# A library that provides a testing suite fot python-telegram-bot
# wich can be found on https://github.com/python-telegram-bot/python-telegram-bot
# which can be found on https://github.com/python-telegram-bot/python-telegram-bot
# Copyright (C) 2017
# Pieter Schutz - https://github.com/eldinnie
#
Expand All @@ -18,14 +18,15 @@
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
"""This module provides a helperclass to transform marked_up messages to plaintext with entities"""
"""This module provides a helper class to transform marked_up messages to plaintext with entities"""
import re

from ptbtest.errors import BadMarkupException
from telegram import MessageEntity

from ptbtest.errors import BadMarkupException


class EntityParser():
class EntityParser:
"""
Placeholder class for the static parser methods
"""
Expand All @@ -45,9 +46,8 @@ def parse_markdown(message):
the message after parsing.
"""
invalids = re.compile(
r'''(\*_|\*```|\*`|\*\[.*?\]\(.*?\)|_\*|_```|_`|_\[.*?\]\(.*?\)|```\*|```_|
```\[.*?\]\(.*?\)|`\*|`_|`\[.*?\]\(.*?\)|\[.*?\]\(.*?\)\*|
\[.*?\]\(.*?\)_|\[.*?\]\(.*?\)```|\[.*?\]\(.*?\)`)'''
r'(\*_|\*```|\*`|\*\[.*?\]\(.*?\)|_\*|_```|_`|_\[.*?\]\(.*?\)|```\*|```_|```\[.*?\]\(.*?\)'
r'|`\*|`_|`\[.*?\]\(.*?\)|\[.*?\]\(.*?\)\*|\[.*?\]\(.*?\)_|\[.*?\]\(.*?\)```|\[.*?\]\(.*?\)`)'
)
tags = re.compile(r'(([`]{3}|\*|_|`)(.*?)(\2))')
text_links = re.compile(r'(\[(?P<text>.*?)\]\((?P<url>.*?)\))')
Expand All @@ -66,25 +66,25 @@ def parse_html(message):
(message(str), entities(list(telegram.MessageEntity))): The entities found in the message and
the message after parsing.
"""
invalids = re.compile(r'''(<b><i>|<b><pre>|<b><code>|<b>(<a.*?>)|
<i><b>|<i><pre>|<i><code>|<i>(<a.*?>)|
<pre><b>|<pre><i>|<pre><code>|<pre>(<a.*?>)|
<code><b>|<code><i>|<code><pre>|<code>(<a.*?>)|
(<a.*>)?<b>|(<a.*?>)<i>|(<a.*?>)<pre>|(<a.*?>)<code>)'''
invalids = re.compile(r'(<b><i>|<b><pre>|<b><code>|<b>(<a.*?>)|<i><b>|<i><pre>'
r'|<i><code>|<i>(<a.*?>)|<pre><b>|<pre><i>|<pre><code>|<pre>(<a.*?>)'
r'|<code><b>|<code><i>|<code><pre>|<code>(<a.*?>)'
r'| {35}(<a.*>)?<b>|(<a.*?>)<i>|(<a.*?>)<pre>|(<a.*?>)<code>)'
# TODO: Without the ` {35}` a test breaks. Please investigate the tag for typos.
)
tags = re.compile(r'(<(b|i|pre|code)>(.*?)<\/\2>)')
tags = re.compile(r'(<(b|i|pre|code)>(.*?)</\2>)')
text_links = re.compile(
r'<a href=[\'\"](?P<url>.*?)[\'\"]>(?P<text>.*?)<\/a>')
r'<a href=[\'\"](?P<url>.*?)[\'\"]>(?P<text>.*?)</a>')

return EntityParser.__parse_text("HTML", message, invalids, tags,
text_links)

@staticmethod
def __parse_text(ptype, message, invalids, tags, text_links):
entities = []
mentions = re.compile(r'@[a-zA-Z0-9]{1,}\b')
hashtags = re.compile(r'#[a-zA-Z0-9]{1,}\b')
botcommands = re.compile(r'(?<!\/|\w)\/[a-zA-Z0-0_\-]{1,}\b')
mentions = re.compile(r'@[a-zA-Z0-9]+\b')
hashtags = re.compile(r'#[a-zA-Z0-9]+\b')
botcommands = re.compile(r'(?<!/|\w)/[a-zA-Z0_\-]+\b')
urls = re.compile(
r'(([hHtTpP]{4}[sS]?|[fFtTpP]{3})://)?([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?'
)
Expand All @@ -105,7 +105,8 @@ def __parse_text(ptype, message, invalids, tags, text_links):
parse_type = "code"
elif tag.groups()[1] in ["pre", "```"]:
parse_type = "pre"
entities.append(MessageEntity(parse_type, start, len(text)))
entities.append(MessageEntity(parse_type, start, len(
text))) # TODO: What if an invalid tag gets passed? Should probably throw exception.
message = tags.sub(r'\3', message, count=1)
while text_links.search(message):
link = text_links.search(message)
Expand All @@ -121,13 +122,15 @@ def __parse_text(ptype, message, invalids, tags, text_links):
for mention in mentions.finditer(message):
entities.append(
MessageEntity('mention',
mention.start(), mention.end() - mention.start(
)))
mention.start(), mention.end() - mention.start()
)
)
for hashtag in hashtags.finditer(message):
entities.append(
MessageEntity('hashtag',
hashtag.start(), hashtag.end() - hashtag.start(
)))
hashtag.start(), hashtag.end() - hashtag.start()
)
)
for botcommand in botcommands.finditer(message):
entities.append(
MessageEntity('bot_command',
Expand Down
2 changes: 1 addition & 1 deletion ptbtest/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# pylint: disable=E0611,E0213,E1102,C0103,E1101,W0613,R0913,R0904
#
# A library that provides a testing suite fot python-telegram-bot
# wich can be found on https://github.com/python-telegram-bot/python-telegram-bot
# which can be found on https://github.com/python-telegram-bot/python-telegram-bot
# Copyright (C) 2017
# Pieter Schutz - https://github.com/eldinnie
#
Expand Down
14 changes: 8 additions & 6 deletions ptbtest/inlinequerygenerator.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# pylint: disable=E0611,E0213,E1102,C0103,E1101,W0613,R0913,R0904
#
# A library that provides a testing suite fot python-telegram-bot
# wich can be found on https://github.com/python-telegram-bot/python-telegram-bot
# which can be found on https://github.com/python-telegram-bot/python-telegram-bot
# Copyright (C) 2017
# Pieter Schutz - https://github.com/eldinnie
#
Expand All @@ -22,11 +22,12 @@
import uuid

from telegram import ChosenInlineResult
from .updategenerator import update
from .ptbgenerator import PtbGenerator
from telegram import (InlineQuery, Location, User)

from ptbtest import (Mockbot, UserGenerator)
from ptbtest.errors import (BadBotException, BadUserException)
from telegram import (InlineQuery, Location, User)
from .ptbgenerator import PtbGenerator
from .updategenerator import update


class InlineQueryGenerator(PtbGenerator):
Expand All @@ -37,7 +38,7 @@ class InlineQueryGenerator(PtbGenerator):
bot (ptbtest.Mockbot): Bot to encode with the messages
Args:
bot (Optional[ptbtest.Mockbot]): supply your own for a custom botname
bot (Optional[ptbtest.Mockbot]): supply your own for a custom bot name
"""

def __init__(self, bot=None):
Expand Down Expand Up @@ -160,5 +161,6 @@ def get_chosen_inline_result(self,
location=location,
inline_message_id=inline_message_id)

def _gen_id(self):
@staticmethod
def _gen_id():
return str(uuid.uuid4())

0 comments on commit 01bdd34

Please sign in to comment.