Skip to content

Commit

Permalink
[refactoring] tests + contrib
Browse files Browse the repository at this point in the history
  • Loading branch information
AidarAzizov committed Apr 5, 2024
1 parent 50a6c87 commit 957d223
Show file tree
Hide file tree
Showing 9 changed files with 19,947 additions and 8 deletions.
1 change: 1 addition & 0 deletions .github/workflows/python-package.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ jobs:
- name: Install dependencies
run: |
python -m pip install --upgrade pip
python setup.py install
python -m pip install flake8 pytest
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
- name: Lint with flake8
Expand Down
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
# Compiled, optimized or cached files.
.cache/
__pycache__/
.pytest_cache/
*.py[cod]
*$py.class
build/

# Bot example log.
/example/log/
Expand Down
22 changes: 22 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# Contribute
## Pull request
Если вы решили впервые стать контрибьютером и помочь развитию open-source проекта, этот пункт для вас.
1) Делается fork основного репозитория
2) git clone https://github.com/ваш-логин/bot-python.git
3) Локальное изменение
4) Сделайте ребейз на remote master ветку
5) git push origin <ваш-логин>
6) В удаленном репозитории нажать _compare&pull request_

Также рекомендуем ознакомиться с подробной инструкцией для контрибьютеров -- README.md

## Tests
1) Если добавляется новая функциональность, то покрывайте ее тестами
2) Следите за тем, чтобы тесты успешно выполнялись в PR перед мержем.

## Merge
Ветка будет смержена в мастер, когда:
1) Все пайплайны пройдут успешно
2) Новая функциональность будет покрыта тестами

После выполнения всех пунктов один из сотрудников проверит в ближайшее время PR и смержит его.
8 changes: 5 additions & 3 deletions bot/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,11 @@ def _start_polling(self):
if response:
if "description" in response.json() and response.json()["description"] == 'Invalid token':
raise InvalidToken(response.json())

for event in response.json()["events"]:
self.dispatcher.dispatch(Event(type_=EventType(event["type"]), data=event["payload"]))

if "events" in response.json():
for event in response.json()["events"]:
self.dispatcher.dispatch(Event(type_=EventType(event["type"]), data=event["payload"]))

except InvalidToken as e:
self.log.exception("InvalidToken: {e}".format(e=e))
sleep(5)
Expand Down
20 changes: 15 additions & 5 deletions example/test_bot.py → example/hidden_test_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import json
import logging.config
from os import path
from threading import Thread
from time import sleep
import sys
from bot.bot import Bot
Expand All @@ -10,6 +11,10 @@
CommandHandler, NewChatMembersHandler, LeftChatMembersHandler, PinnedMessageHandler, UnPinnedMessageHandler, \
EditedMessageHandler, DeletedMessageHandler, StartCommandHandler, BotButtonCommandHandler

from server import startServer

import pytest

if sys.version_info[0] == 3:
from gtts import gTTS

Expand All @@ -23,17 +28,17 @@
OWNER = "XXXXXXXXX"
TEST_CHAT = "XXXXX"
TEST_USER = "XXXXX"
API_URL = "https://api.icq.net/bot/v1"
API_URL = "http://localhost:8080"


def start_cb(bot, event):
bot.send_text(chat_id=event.data['chat']['chatId'], text="Hello! Let's start!")


@pytest.fixture
def help_cb(bot, event):
bot.send_text(chat_id=event.data['chat']['chatId'], text="Some message help")


@pytest.fixture
def test_cb(bot, event):
bot.send_text(chat_id=event.data['chat']['chatId'], text="User command: {}".format(event.data['text']))

Expand Down Expand Up @@ -197,7 +202,7 @@ def buttons_answer_cb(bot, event):
)


def main():
def start_client():
# Creating a new bot instance.
bot = Bot(token=TOKEN, name=NAME, version=VERSION, api_url_base=API_URL)

Expand Down Expand Up @@ -259,7 +264,7 @@ def main():
bot.dispatcher.add_handler(MessageHandler(filters=Filter.text, callback=message_cb))

# Handler with regexp filter
bot.dispatcher.add_handler(MessageHandler(filters=Filter.regexp("^\d*$"), callback=regexp_only_dig_cb))
bot.dispatcher.add_handler(MessageHandler(filters=Filter.regexp("^\\d*$"), callback=regexp_only_dig_cb))

# Handler for no media file. For example, text file
bot.dispatcher.add_handler(MessageHandler(filters=Filter.data, callback=file_cb))
Expand Down Expand Up @@ -403,6 +408,11 @@ def main():

bot.idle()

def main():
thread = Thread(target = startServer)
thread.start()
start_client()
thread.join()

if __name__ == "__main__":
main()
137 changes: 137 additions & 0 deletions example/server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
# Python 3 server example
from http.server import BaseHTTPRequestHandler, HTTPServer
import time
import urllib.parse as urlparse



hostName = "localhost"
serverPort = 8080

class MyServer(BaseHTTPRequestHandler):

def do_GET(self):
self._do()
def do_POST(self):
self._do()
def do_DELETE(self):
self._do()
def do_HEAD(self):
self._do()

def _do(self):
o = urlparse.urlparse(self.path)
query_params = urlparse.parse_qs(o.query)

self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()

if 'token' not in query_params:
self.tokenError()

if o.path == '/self/get':# добавить проверку параметров в куери парамсах
self.wfile.write(bytes(self._SelfGet(), 'utf-8'))
elif o.path == '/events/get':
self.wfile.write(bytes(self._EventsGet(), 'utf-8'))
elif o.path == '/chats/getInfo':
self.wfile.write(bytes(self._GetInfo(), 'utf-8'))
else:
self.defaultOk()



def _SelfGet(self):
return "{\
\"firstName\": \"test_bot\",\
\"nick\": \"test_bot\",\
\"userId\": \"100000\",\
\"ok\": true\
}"

def _EventsGet(self):
return "{\
\"ok\": true,\
\"events\": [\
{\
\"eventId\": 1,\
\"type\": \"newMessage\",\
\"payload\": {\
\"msgId\": \"57883346846815030\",\
\"chat\": {\
\"chatId\": \"[email protected]\",\
\"type\": \"channel\",\
\"title\": \"The best channel\"\
},\
\"from\": {\
\"userId\": \"1234567890\",\
\"firstName\": \"Name\",\
\"lastName\": \"SurName\"\
},\
\"timestamp\": 1546290000,\
\"text\": \"Hello!\",\
\"parts\": [\
{\
\"type\": \"sticker\",\
\"payload\": {\
\"fileId\": \"2IWuJzaNWCJZxJWCvZhDYuJ5XDsr7hU\"\
}\
}\
]\
}\
},\
{\
\"eventId\": 2,\
\"type\": \"editedMessage\",\
\"payload\": {\
\"msgId\": \"57883346846815030\",\
\"chat\": {\
\"chatId\": \"[email protected]\",\
\"type\": \"channel\",\
\"title\": \"The best channel\"\
},\
\"from\": {\
\"userId\": \"1234567890\",\
\"firstName\": \"Name\",\
\"lastName\": \"SurName\"\
},\
\"timestamp\": 1546290000,\
\"text\": \"Hello!\",\
\"editedTimestamp\": 1546290099\
}\
}\
]\
}"

def _GetInfo(self):
return "{\
\"about\": \"some text\",\
\"firstName\": \"first\",\
\"language\": \"en\",\
\"lastName\": \"last\",\
\"type\": \"private\",\
\"ok\": true\
}"

def tokenError(self):
self.wfile.write(bytes("{\"ok\": false, \"description\": \"Invalid token\"}", "utf-8"))

def badRequest(self):
self.wfile.write(bytes("{\"ok\": false, \"description\": \"bad request\"}", "utf-8"))

def defaultOk(self):
self.wfile.write(bytes("{\"ok\": true, \"description\": \"ok\"}", "utf-8"))


def startServer():
webServer = HTTPServer((hostName, serverPort), MyServer)

try:
webServer.serve_forever()
except KeyboardInterrupt:
pass

webServer.server_close()

if __name__ == "__main__":
startServer()
80 changes: 80 additions & 0 deletions example/test_bot_new.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
from http.server import HTTPServer
import pytest
from bot.bot import Bot
from threading import Thread

import server

NAME = ""
VERSION = "0.0.0"
TOKEN = "XXX.XXXXXXXXXX.XXXXXXXXXX:XXXXXXXXX"
OWNER = "XXXXXXXXX"
TEST_CHAT = "XXXXX"
TEST_USER = "XXXXX"
API_URL = "http://localhost:8080"



bot = Bot(token=TOKEN, api_url_base=API_URL, is_myteam=True)

@pytest.fixture(scope='session', autouse=True)
def launch_server():
thread = Thread(target = server.startServer)
thread.daemon = True
thread.start()


def test_EventsGet():
response = bot.events_get(1, 0)
if "description" in response.json():
pytest.xfail(response.json()["description"])

assert "events" in response.json()
for event in response.json()["events"]:
if "type" not in event or "payload" not in event:
pytest.xfail("Bad format of response")



def test_SelfGet():
response = bot.self_get()
if "description" in response.json():
pytest.xfail(response.json()["description"])

if "ok" not in response.json() or response.json()["ok"] is False:
pytest.xfail("Answer isn't ok")

if "firstName" not in response.json() or "nick" not in response.json() or \
"userId" not in response.json() :
pytest.xfail(response.json()["description"])



def test_chats_GetInfo_OK():
response = bot.get_chat_info(TEST_CHAT)
assert response

if "description" in response.json():
pytest.xfail(response.json()["description"])

if "ok" not in response.json() or response.json()["ok"] is False:
pytest.xfail("Answer isn't ok")

if "about" not in response.json() or "language" not in response.json() or \
"firstName" not in response.json() or "lastName" not in response.json():
pytest.xfail("Bad format of response 'getInfo'")




def test_chats_GetInfo_ERROR():
response = bot.get_chat_info("111")


def test_plug_error():
pytest.xfail("Plug")


def test_plug_ok():
pass

Loading

0 comments on commit 957d223

Please sign in to comment.