diff --git a/requirements.txt b/requirements.txt index cb79cb87732bddcba1798d8eb1096777a17b6cad..e715e13c2b5616f080d0fc4cee74fd302f9e9f38 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,2 @@ -pretenders ucoinpy>=0.13 -git+https://github.com/Insoleet/quamash.git@sockets_only \ No newline at end of file +quamash \ No newline at end of file diff --git a/run_tests.py b/run_tests.py index 90bdbf08f9a68ee174d8f58c145b9496a4af1351..33a8c0d73b5e961e30ca3da5bd3d27127a40a1ae 100644 --- a/run_tests.py +++ b/run_tests.py @@ -5,29 +5,34 @@ import unittest import subprocess import time import shlex +from optparse import OptionParser -cmd = 'python -m pretenders.server.server --host 127.0.0.1 --port 50000' +parser = OptionParser() -p = subprocess.Popen(shlex.split(cmd)) -time.sleep(2) -# Force saves to be done in temp directory -os.environ["XDG_CONFIG_HOME"] = os.path.join(os.path.dirname(__file__), 'temp') -sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'lib'))) -sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), 'src'))) -try: - print("Run") - runner = unittest.TextTestRunner().run(unittest.defaultTestLoader.discover(start_dir='sakia.tests', pattern='test_*')) -finally: - print("Terminate") - os.kill(p.pid, signal.SIGINT) - time.sleep(2) - try: +parser.add_option("-u", "--unit", + action="store_true", dest="unit", default=False, + help="Run unit tests") - if sys.platform == "linux": - os.kill(p.pid, signal.SIGKILL) - p.kill() - print("Hard killed") - except OSError: - print("Terminated gracefully") +parser.add_option("-f", "--functional", + action="store_true", dest="functional", default=False, + help="Run functional tests") + +parser.add_option("-a", "--all", + action="store_true", dest="all", default=False, + help="Run all tests") +options, args = parser.parse_args(sys.argv) + +if options.unit: + runner = unittest.TextTestRunner().run(unittest.defaultTestLoader.discover(start_dir='sakia.tests.unit', + pattern='test_*')) +elif options.functional: + runner = unittest.TextTestRunner().run(unittest.defaultTestLoader.discover(start_dir='sakia.tests.functional', + pattern='test_*')) +elif options.all: + runner = unittest.TextTestRunner().run(unittest.defaultTestLoader.discover(start_dir='sakia.tests', + pattern='test_*')) +else: + parser.print_help() + sys.exit(1) sys.exit(not runner.wasSuccessful()) \ No newline at end of file diff --git a/src/sakia/core/community.py b/src/sakia/core/community.py index c0832ca379c4a0651922df2efba3120280c96501..bc97eddeb913a1d9a7976a7e4c9772b4ef674204 100644 --- a/src/sakia/core/community.py +++ b/src/sakia/core/community.py @@ -173,7 +173,7 @@ class Community(QObject): else: return None except ValueError as e: - if '404' in e: + if '404' in str(e): logging.debug(str(e)) return None except NoPeerAvailable as e: diff --git a/src/sakia/core/net/api/bma/access.py b/src/sakia/core/net/api/bma/access.py index a0445b1a92ab3f45eb4bf8c96a5f4408ba2813d3..bd72e65e3616e7a9dda18fe5e71316f81f0e4f0a 100644 --- a/src/sakia/core/net/api/bma/access.py +++ b/src/sakia/core/net/api/bma/access.py @@ -243,7 +243,7 @@ class BmaAccess(QObject): if '404' in str(e) or '400' in str(e): raise tries += 1 - except (ClientError, gaierror, asyncio.TimeoutError): + except (ClientError, gaierror, asyncio.TimeoutError) as e: tries += 1 except jsonschema.ValidationError as e: logging.debug(str(e)) @@ -274,7 +274,7 @@ class BmaAccess(QObject): if '404' in str(e) or '400' in str(e): raise tries += 1 - except (ClientError, gaierror, asyncio.TimeoutError): + except (ClientError, gaierror, asyncio.TimeoutError) as e: tries += 1 except jsonschema.ValidationError as e: logging.debug(str(e)) diff --git a/src/sakia/gui/certification.py b/src/sakia/gui/certification.py index 118fd80bc29fd510c23b0dc177719f1f49f92a3d..64c46ace1aa5921dcd61031d25d344d00e0f339c 100644 --- a/src/sakia/gui/certification.py +++ b/src/sakia/gui/certification.py @@ -13,7 +13,7 @@ from PyQt5.QtCore import Qt from ..gen_resources.certification_uic import Ui_CertificationDialog from sakia.gui.widgets import toast from sakia.gui.widgets.dialogs import QAsyncMessageBox -from ..tools.decorators import asyncify +from ..tools.decorators import asyncify, once_at_a_time from ..tools.exceptions import NoPeerAvailable @@ -84,8 +84,10 @@ class CertificationDialog(QDialog, Ui_CertificationDialog): def change_current_community(self, index): self.community = self.account.communities[index] - self.refresh() + if self.isVisible(): + self.refresh() + @once_at_a_time @asyncify async def refresh(self): account_identity = await self.account.identity(self.community) @@ -114,4 +116,5 @@ class CertificationDialog(QDialog, Ui_CertificationDialog): future = asyncio.Future() self.finished.connect(lambda r: future.set_result(r)) self.open() + self.refresh() return future diff --git a/src/sakia/tests/__init__.py b/src/sakia/tests/__init__.py index 7d9d5e42eba5e742687cf682486aa68fc6589948..a7d4d00287516418923b1e4dbef7ff519ded3ed1 100644 --- a/src/sakia/tests/__init__.py +++ b/src/sakia/tests/__init__.py @@ -1 +1 @@ -from .quamash_test import QuamashTest \ No newline at end of file +from .quamash_utils import QuamashTest \ No newline at end of file diff --git a/src/sakia/tests/gui/certification/__init__.py b/src/sakia/tests/functional/__init__.py similarity index 100% rename from src/sakia/tests/gui/certification/__init__.py rename to src/sakia/tests/functional/__init__.py diff --git a/src/sakia/tests/gui/identities_tab/__init__.py b/src/sakia/tests/functional/certification/__init__.py similarity index 100% rename from src/sakia/tests/gui/identities_tab/__init__.py rename to src/sakia/tests/functional/certification/__init__.py diff --git a/src/sakia/tests/gui/certification/test_certification.py b/src/sakia/tests/functional/certification/test_certification.py similarity index 89% rename from src/sakia/tests/gui/certification/test_certification.py rename to src/sakia/tests/functional/certification/test_certification.py index 885019c06bf30dcfdf534dc5d888221f4f5b5e36..9900c952965cbc2fd6404baf1832bf8562a29e76 100644 --- a/src/sakia/tests/gui/certification/test_certification.py +++ b/src/sakia/tests/functional/certification/test_certification.py @@ -5,12 +5,10 @@ import quamash import time import logging from ucoinpy.documents.peer import BMAEndpoint -from quamash import QApplication -from PyQt5.QtWidgets import QDialog, QDialogButtonBox, QMessageBox +from PyQt5.QtWidgets import QDialog, QDialogButtonBox, QMessageBox, QApplication from PyQt5.QtCore import QLocale, Qt from PyQt5.QtTest import QTest from ucoinpy.api.bma import API -from sakia.tests.mocks.monkeypatch import pretender_reversed from sakia.tests.mocks.bma import init_new_community from sakia.core.registry.identities import IdentitiesRegistry from sakia.gui.certification import CertificationDialog @@ -32,7 +30,7 @@ class TestCertificationDialog(unittest.TestCase, QuamashTest): self.application = Application(self.qapplication, self.lp, self.identities_registry) self.application.preferences['notifications'] = False - self.endpoint = BMAEndpoint("", "127.0.0.1", "", 50000) + self.endpoint = BMAEndpoint("", "127.0.0.1", "", 50010) self.node = Node("test_currency", [self.endpoint], "", "HnFcSms8jzwngtVomTTnzudZx7SHUQY8sVE1y8yBmULk", None, Node.ONLINE, @@ -57,15 +55,16 @@ class TestCertificationDialog(unittest.TestCase, QuamashTest): self.tearDownQuamash() def test_certification_init_community(self): - mock = init_new_community.get_mock() + mock = init_new_community.get_mock(self.lp) time.sleep(2) - logging.debug(mock.pretend_url) - API.reverse_url = pretender_reversed(mock.pretend_url) certification_dialog = CertificationDialog(self.application, self.account, self.password_asker) - async def open_dialog(certification_dialog): + async def open_dialog(certification_dialog): + srv, port, url = await mock.create_server() + self.endpoint.port = port + result = await certification_dialog.async_exec() self.assertEqual(result, QDialog.Accepted) @@ -73,7 +72,7 @@ class TestCertificationDialog(unittest.TestCase, QuamashTest): if certification_dialog.isVisible(): certification_dialog.close() - async def exec_test(): + async def exec_test(): await asyncio.sleep(1) QTest.mouseClick(certification_dialog.radio_pubkey, Qt.LeftButton) QTest.keyClicks(certification_dialog.edit_pubkey, "FADxcH5LmXGmGFgdixSes6nWnC4Vb4pRUBYT81zQRhjn") @@ -87,7 +86,6 @@ class TestCertificationDialog(unittest.TestCase, QuamashTest): self.lp.call_later(15, close_dialog) asyncio.ensure_future(exec_test()) self.lp.run_until_complete(open_dialog(certification_dialog)) - mock.delete_mock() if __name__ == '__main__': diff --git a/src/sakia/tests/gui/main_window/__init__.py b/src/sakia/tests/functional/identities_tab/__init__.py similarity index 100% rename from src/sakia/tests/gui/main_window/__init__.py rename to src/sakia/tests/functional/identities_tab/__init__.py diff --git a/src/sakia/tests/gui/identities_tab/test_identities_table.py b/src/sakia/tests/functional/identities_tab/test_identities_table.py similarity index 88% rename from src/sakia/tests/gui/identities_tab/test_identities_table.py rename to src/sakia/tests/functional/identities_tab/test_identities_table.py index 1ad2e3ac65c91a5a630c83683f535b139f7c3211..1ee8398f40753eeef938ca1953f643c9bd2cabd9 100644 --- a/src/sakia/tests/gui/identities_tab/test_identities_table.py +++ b/src/sakia/tests/functional/identities_tab/test_identities_table.py @@ -9,7 +9,7 @@ from PyQt5.QtCore import QLocale, Qt, QPoint from PyQt5.QtTest import QTest from ucoinpy.api import bma from ucoinpy.api.bma import API -from sakia.tests.mocks.monkeypatch import pretender_reversed + from sakia.tests.mocks.bma import nice_blockchain from sakia.core.registry.identities import IdentitiesRegistry from sakia.gui.identities_tab import IdentitiesTabWidget @@ -31,7 +31,7 @@ class TestIdentitiesTable(unittest.TestCase, QuamashTest): self.application = Application(self.qapplication, self.lp, self.identities_registry) self.application.preferences['notifications'] = False - self.endpoint = BMAEndpoint("", "127.0.0.1", "", 50000) + self.endpoint = BMAEndpoint("", "127.0.0.1", "", 50002) self.node = Node("test_currency", [self.endpoint], "", "HnFcSms8jzwngtVomTTnzudZx7SHUQY8sVE1y8yBmULk", None, Node.ONLINE, @@ -56,13 +56,9 @@ class TestIdentitiesTable(unittest.TestCase, QuamashTest): self.tearDownQuamash() def test_search_identity_found(self): - mock = nice_blockchain.get_mock() + mock = nice_blockchain.get_mock(self.lp) time.sleep(2) - logging.debug(mock.pretend_url) - API.reverse_url = pretender_reversed(mock.pretend_url) identities_tab = IdentitiesTabWidget(self.application) - identities_tab.change_account(self.account, self.password_asker) - identities_tab.change_community(self.community) future = asyncio.Future() def open_widget(): @@ -74,8 +70,13 @@ class TestIdentitiesTable(unittest.TestCase, QuamashTest): identities_tab.close() future.set_result(True) - async def exec_test(): - await asyncio.sleep(2) + async def exec_test(): + srv, port, url = await mock.create_server() + self.endpoint.port = port + + identities_tab.change_account(self.account, self.password_asker) + identities_tab.change_community(self.community) + await asyncio.sleep(1) urls = [mock.get_request(i).url for i in range(0, 7)] self.assertTrue('/wot/certifiers-of/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ' in urls, msg="Not found in {0}".format(urls)) @@ -91,7 +92,7 @@ class TestIdentitiesTable(unittest.TestCase, QuamashTest): QTest.keyClicks(identities_tab.edit_textsearch, "doe") QTest.mouseClick(identities_tab.button_search, Qt.LeftButton) await asyncio.sleep(2) - req = 7 + req = 8 self.assertEqual(mock.get_request(req).method, 'GET') self.assertEqual(mock.get_request(req).url, @@ -105,7 +106,6 @@ class TestIdentitiesTable(unittest.TestCase, QuamashTest): asyncio.ensure_future(exec_test()) self.lp.call_later(15, close_dialog) self.lp.run_until_complete(open_widget()) - mock.delete_mock() if __name__ == '__main__': logging.basicConfig( stream=sys.stderr ) diff --git a/src/sakia/tests/gui/preferences/__init__.py b/src/sakia/tests/functional/main_window/__init__.py similarity index 100% rename from src/sakia/tests/gui/preferences/__init__.py rename to src/sakia/tests/functional/main_window/__init__.py diff --git a/src/sakia/tests/gui/main_window/test_main_window_dialogs.py b/src/sakia/tests/functional/main_window/test_main_window_dialogs.py similarity index 100% rename from src/sakia/tests/gui/main_window/test_main_window_dialogs.py rename to src/sakia/tests/functional/main_window/test_main_window_dialogs.py diff --git a/src/sakia/tests/gui/main_window/test_main_window_menus.py b/src/sakia/tests/functional/main_window/test_main_window_menus.py similarity index 100% rename from src/sakia/tests/gui/main_window/test_main_window_menus.py rename to src/sakia/tests/functional/main_window/test_main_window_menus.py diff --git a/src/sakia/tests/gui/process_cfg_account/__init__.py b/src/sakia/tests/functional/preferences/__init__.py similarity index 100% rename from src/sakia/tests/gui/process_cfg_account/__init__.py rename to src/sakia/tests/functional/preferences/__init__.py diff --git a/src/sakia/tests/gui/preferences/test_preferences_dialog.py b/src/sakia/tests/functional/preferences/test_preferences_dialog.py similarity index 100% rename from src/sakia/tests/gui/preferences/test_preferences_dialog.py rename to src/sakia/tests/functional/preferences/test_preferences_dialog.py diff --git a/src/sakia/tests/gui/process_cfg_community/__init__.py b/src/sakia/tests/functional/process_cfg_account/__init__.py similarity index 100% rename from src/sakia/tests/gui/process_cfg_community/__init__.py rename to src/sakia/tests/functional/process_cfg_account/__init__.py diff --git a/src/sakia/tests/gui/process_cfg_account/test_add_account.py b/src/sakia/tests/functional/process_cfg_account/test_add_account.py similarity index 98% rename from src/sakia/tests/gui/process_cfg_account/test_add_account.py rename to src/sakia/tests/functional/process_cfg_account/test_add_account.py index 604967d42715edc2aa4209f7b733528f6626ef67..3143f9ee1a74ce283848b92155477857c49b01d3 100644 --- a/src/sakia/tests/gui/process_cfg_account/test_add_account.py +++ b/src/sakia/tests/functional/process_cfg_account/test_add_account.py @@ -38,7 +38,7 @@ class ProcessAddCommunity(unittest.TestCase, QuamashTest): process_account = ProcessConfigureAccount(self.application, None) - async def open_dialog(process_account): + async def open_dialog(process_account): result = await process_account.async_exec() self.assertEqual(result, QDialog.Accepted) @@ -46,7 +46,7 @@ class ProcessAddCommunity(unittest.TestCase, QuamashTest): if process_account.isVisible(): process_account.close() - async def exec_test(): + async def exec_test(): QTest.keyClicks(process_account.edit_account_name, "test") self.assertEqual(process_account.stacked_pages.currentWidget(), process_account.page_init, diff --git a/src/sakia/tests/gui/transfer/__init__.py b/src/sakia/tests/functional/process_cfg_community/__init__.py similarity index 100% rename from src/sakia/tests/gui/transfer/__init__.py rename to src/sakia/tests/functional/process_cfg_community/__init__.py diff --git a/src/sakia/tests/gui/process_cfg_community/test_add_community.py b/src/sakia/tests/functional/process_cfg_community/test_add_community.py similarity index 84% rename from src/sakia/tests/gui/process_cfg_community/test_add_community.py rename to src/sakia/tests/functional/process_cfg_community/test_add_community.py index 010d042438e8dff85d183e38d15b02931d29ba87..48eb9ba82d247dcb77c6c9636158319a63699dd2 100644 --- a/src/sakia/tests/gui/process_cfg_community/test_add_community.py +++ b/src/sakia/tests/functional/process_cfg_community/test_add_community.py @@ -7,8 +7,6 @@ import time from PyQt5.QtWidgets import QDialog from PyQt5.QtCore import QLocale, Qt from PyQt5.QtTest import QTest -from ucoinpy.api.bma import API -from sakia.tests.mocks.monkeypatch import pretender_reversed from sakia.tests.mocks.bma import new_blockchain, nice_blockchain from sakia.core.registry.identities import IdentitiesRegistry from sakia.gui.process_cfg_community import ProcessConfigureCommunity @@ -38,10 +36,8 @@ class ProcessAddCommunity(unittest.TestCase, QuamashTest): self.tearDownQuamash() def test_register_community_empty_blockchain(self): - mock = new_blockchain.get_mock() + mock = new_blockchain.get_mock(self.lp) time.sleep(2) - logging.debug(mock.pretend_url) - API.reverse_url = pretender_reversed(mock.pretend_url) process_community = ProcessConfigureCommunity(self.application, self.account, None, self.password_asker) @@ -50,17 +46,18 @@ class ProcessAddCommunity(unittest.TestCase, QuamashTest): if process_community.isVisible(): process_community.close() - async def exec_test(): + async def exec_test(): + srv, port, url = await mock.create_server() await asyncio.sleep(1) QTest.mouseClick(process_community.lineedit_server, Qt.LeftButton) QTest.keyClicks(process_community.lineedit_server, "127.0.0.1") QTest.mouseDClick(process_community.spinbox_port, Qt.LeftButton) - process_community.spinbox_port.setValue(50000) + process_community.spinbox_port.setValue(port) self.assertEqual(process_community.stacked_pages.currentWidget(), process_community.page_node, msg="Current widget : {0}".format(process_community.stacked_pages.currentWidget().objectName())) self.assertEqual(process_community.lineedit_server.text(), "127.0.0.1") - self.assertEqual(process_community.spinbox_port.value(), 50000) + self.assertEqual(process_community.spinbox_port.value(), port) QTest.mouseClick(process_community.button_register, Qt.LeftButton) await asyncio.sleep(1) self.assertEqual(mock.get_request(0).method, 'GET') @@ -75,14 +72,14 @@ class ProcessAddCommunity(unittest.TestCase, QuamashTest): await asyncio.sleep(5) self.assertEqual(mock.get_request(5).method, 'GET') self.assertEqual(mock.get_request(5).url, - '/wot/certifiers-of/john') - for i in range(6, 9): + '/wot/lookup/john') + for i in range(6, 8): self.assertEqual(mock.get_request(i).method, 'GET') self.assertEqual(mock.get_request(i).url, '/wot/lookup/john') - self.assertEqual(mock.get_request(9).url[:8], '/wot/add') - self.assertEqual(mock.get_request(9).method, 'POST') + self.assertEqual(mock.get_request(8).url[:8], '/wot/add') + self.assertEqual(mock.get_request(8).method, 'POST') self.assertEqual(process_community.label_error.text(), "Broadcasting identity...") await asyncio.sleep(1) @@ -95,13 +92,10 @@ class ProcessAddCommunity(unittest.TestCase, QuamashTest): asyncio.ensure_future(exec_test()) self.lp.run_until_complete(process_community.async_exec()) self.assertEqual(process_community.result(), QDialog.Accepted) - mock.delete_mock() def test_connect_community_empty_blockchain(self): - mock = new_blockchain.get_mock() + mock = new_blockchain.get_mock(self.lp) time.sleep(2) - logging.debug(mock.pretend_url) - API.reverse_url = pretender_reversed(mock.pretend_url) process_community = ProcessConfigureCommunity(self.application, self.account, None, self.password_asker) @@ -110,23 +104,23 @@ class ProcessAddCommunity(unittest.TestCase, QuamashTest): if process_community.isVisible(): process_community.close() - async def exec_test(): + async def exec_test(): + srv, port, url = await mock.create_server() + await asyncio.sleep(1) QTest.mouseClick(process_community.lineedit_server, Qt.LeftButton) QTest.keyClicks(process_community.lineedit_server, "127.0.0.1") QTest.mouseDClick(process_community.spinbox_port, Qt.LeftButton) - process_community.spinbox_port.setValue(50000) + process_community.spinbox_port.setValue(port) self.assertEqual(process_community.stacked_pages.currentWidget(), process_community.page_node, msg="Current widget : {0}".format(process_community.stacked_pages.currentWidget().objectName())) self.assertEqual(process_community.lineedit_server.text(), "127.0.0.1") - self.assertEqual(process_community.spinbox_port.value(), 50000) + self.assertEqual(process_community.spinbox_port.value(), port) QTest.mouseClick(process_community.button_connect, Qt.LeftButton) - await asyncio.sleep(3) - self.assertNotEqual(mock.get_request(0), None) + await asyncio.sleep(2) self.assertEqual(mock.get_request(0).method, 'GET') self.assertEqual(mock.get_request(0).url, '/network/peering') - self.assertNotEqual(mock.get_request(1), None) self.assertEqual(mock.get_request(1).method, 'GET') self.assertEqual(mock.get_request(1).url, '/wot/certifiers-of/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ') @@ -143,13 +137,10 @@ class ProcessAddCommunity(unittest.TestCase, QuamashTest): self.lp.call_later(15, close_dialog) asyncio.ensure_future(exec_test()) self.lp.run_until_complete(process_community.async_exec()) - mock.delete_mock() def test_connect_community_wrong_pubkey(self): - mock = nice_blockchain.get_mock() + mock = nice_blockchain.get_mock(self.lp) time.sleep(2) - logging.debug(mock.pretend_url) - API.reverse_url = pretender_reversed(mock.pretend_url) self.account.pubkey = "wrong_pubkey" process_community = ProcessConfigureCommunity(self.application, self.account, @@ -159,26 +150,25 @@ class ProcessAddCommunity(unittest.TestCase, QuamashTest): if process_community.isVisible(): process_community.close() - async def exec_test(): + async def exec_test(): + srv, port, url = await mock.create_server() await asyncio.sleep(1) QTest.mouseClick(process_community.lineedit_server, Qt.LeftButton) QTest.keyClicks(process_community.lineedit_server, "127.0.0.1") QTest.mouseDClick(process_community.spinbox_port, Qt.LeftButton) - process_community.spinbox_port.setValue(50000) + process_community.spinbox_port.setValue(port) self.assertEqual(process_community.stacked_pages.currentWidget(), process_community.page_node, msg="Current widget : {0}".format(process_community.stacked_pages.currentWidget().objectName())) self.assertEqual(process_community.lineedit_server.text(), "127.0.0.1") - self.assertEqual(process_community.spinbox_port.value(), 50000) + self.assertEqual(process_community.spinbox_port.value(), port) QTest.mouseClick(process_community.button_connect, Qt.LeftButton) await asyncio.sleep(1) - self.assertNotEqual(mock.get_request(0), None) self.assertEqual(mock.get_request(0).method, 'GET') self.assertEqual(mock.get_request(0).url, '/network/peering') - self.assertNotEqual(mock.get_request(1), None) self.assertEqual(mock.get_request(1).method, 'GET') self.assertEqual(mock.get_request(1).url, - '/wot/certifiers-of/wrong_pubkey') + '/wot/lookup/john') self.assertEqual(process_community.label_error.text(), """Your pubkey or UID is different on the network. Yours : wrong_pubkey, the network : 7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ""") process_community.close() @@ -187,13 +177,10 @@ Yours : wrong_pubkey, the network : 7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ asyncio.ensure_future(exec_test()) self.lp.run_until_complete(process_community.async_exec()) self.assertEqual(process_community.result(), QDialog.Rejected) - mock.delete_mock() def test_connect_community_wrong_uid(self): - mock = nice_blockchain.get_mock() + mock = nice_blockchain.get_mock(self.lp) time.sleep(2) - logging.debug(mock.pretend_url) - API.reverse_url = pretender_reversed(mock.pretend_url) self.account.name = "wrong_uid" process_community = ProcessConfigureCommunity(self.application, self.account, @@ -203,23 +190,22 @@ Yours : wrong_pubkey, the network : 7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ if process_community.isVisible(): process_community.close() - async def exec_test(): + async def exec_test(): + srv, port, url = await mock.create_server() await asyncio.sleep(1) QTest.mouseClick(process_community.lineedit_server, Qt.LeftButton) QTest.keyClicks(process_community.lineedit_server, "127.0.0.1") QTest.mouseDClick(process_community.spinbox_port, Qt.LeftButton) - process_community.spinbox_port.setValue(50000) + process_community.spinbox_port.setValue(port) self.assertEqual(process_community.stacked_pages.currentWidget(), process_community.page_node, msg="Current widget : {0}".format(process_community.stacked_pages.currentWidget().objectName())) self.assertEqual(process_community.lineedit_server.text(), "127.0.0.1") - self.assertEqual(process_community.spinbox_port.value(), 50000) + self.assertEqual(process_community.spinbox_port.value(), port) QTest.mouseClick(process_community.button_connect, Qt.LeftButton) await asyncio.sleep(1) - self.assertNotEqual(mock.get_request(0), None) self.assertEqual(mock.get_request(0).method, 'GET') self.assertEqual(mock.get_request(0).url, '/network/peering') - self.assertNotEqual(mock.get_request(1), None) self.assertEqual(mock.get_request(1).method, 'GET') self.assertEqual(mock.get_request(1).url, '/wot/certifiers-of/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ') @@ -231,13 +217,10 @@ Yours : wrong_uid, the network : john""") asyncio.ensure_future(exec_test()) self.lp.run_until_complete(process_community.async_exec()) self.assertEqual(process_community.result(), QDialog.Rejected) - mock.delete_mock() def test_connect_community_success(self): - mock = nice_blockchain.get_mock() + mock = nice_blockchain.get_mock(self.lp) time.sleep(2) - logging.debug(mock.pretend_url) - API.reverse_url = pretender_reversed(mock.pretend_url) process_community = ProcessConfigureCommunity(self.application, self.account, None, self.password_asker) @@ -246,23 +229,22 @@ Yours : wrong_uid, the network : john""") if process_community.isVisible(): process_community.close() - async def exec_test(): + async def exec_test(): + srv, port, url = await mock.create_server() await asyncio.sleep(1) QTest.mouseClick(process_community.lineedit_server, Qt.LeftButton) QTest.keyClicks(process_community.lineedit_server, "127.0.0.1") QTest.mouseDClick(process_community.spinbox_port, Qt.LeftButton) - process_community.spinbox_port.setValue(50000) + process_community.spinbox_port.setValue(port) self.assertEqual(process_community.stacked_pages.currentWidget(), process_community.page_node, msg="Current widget : {0}".format(process_community.stacked_pages.currentWidget().objectName())) self.assertEqual(process_community.lineedit_server.text(), "127.0.0.1") - self.assertEqual(process_community.spinbox_port.value(), 50000) + self.assertEqual(process_community.spinbox_port.value(), port) QTest.mouseClick(process_community.button_connect, Qt.LeftButton) await asyncio.sleep(1) - self.assertNotEqual(mock.get_request(0), None) self.assertEqual(mock.get_request(0).method, 'GET') self.assertEqual(mock.get_request(0).url, '/network/peering') - self.assertNotEqual(mock.get_request(1), None) self.assertEqual(mock.get_request(1).method, 'GET') self.assertEqual(mock.get_request(1).url, '/wot/certifiers-of/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ') @@ -274,7 +256,6 @@ Yours : wrong_uid, the network : john""") self.lp.call_later(15, close_dialog) asyncio.ensure_future(exec_test()) self.lp.run_until_complete(process_community.async_exec()) - mock.delete_mock() if __name__ == '__main__': logging.basicConfig( stream=sys.stderr ) diff --git a/src/sakia/tests/functional/transfer/__init__.py b/src/sakia/tests/functional/transfer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/sakia/tests/gui/transfer/test_transfer.py b/src/sakia/tests/functional/transfer/test_transfer.py similarity index 88% rename from src/sakia/tests/gui/transfer/test_transfer.py rename to src/sakia/tests/functional/transfer/test_transfer.py index 3414fc4f23c24e67d1180e413a71229830c40866..cccfc66c1099d1086e43f9791316528c5c21bfc5 100644 --- a/src/sakia/tests/gui/transfer/test_transfer.py +++ b/src/sakia/tests/functional/transfer/test_transfer.py @@ -4,12 +4,11 @@ import asyncio import quamash import time import logging -from quamash import QApplication -from PyQt5.QtWidgets import QDialog, QDialogButtonBox, QMessageBox +from PyQt5.QtWidgets import QDialog, QDialogButtonBox, QMessageBox, QApplication from PyQt5.QtCore import QLocale, Qt from PyQt5.QtTest import QTest from ucoinpy.api.bma import API -from sakia.tests.mocks.monkeypatch import pretender_reversed + from sakia.tests.mocks.bma import nice_blockchain from sakia.core.registry.identities import IdentitiesRegistry from sakia.gui.transfer import TransferMoneyDialog @@ -32,7 +31,7 @@ class TestTransferDialog(unittest.TestCase, QuamashTest): self.application = Application(self.qapplication, self.lp, self.identities_registry) self.application.preferences['notifications'] = False - self.endpoint = BMAEndpoint("", "127.0.0.1", "", 50000) + self.endpoint = BMAEndpoint("", "127.0.0.1", "", 50002) self.node = Node("test_currency", [self.endpoint], "", "HnFcSms8jzwngtVomTTnzudZx7SHUQY8sVE1y8yBmULk", None, Node.ONLINE, @@ -57,10 +56,8 @@ class TestTransferDialog(unittest.TestCase, QuamashTest): self.tearDownQuamash() def test_transfer_nice_community(self): - mock = nice_blockchain.get_mock() + mock = nice_blockchain.get_mock(self.lp) time.sleep(2) - logging.debug(mock.pretend_url) - API.reverse_url = pretender_reversed(mock.pretend_url) transfer_dialog = TransferMoneyDialog(self.application, self.account, self.password_asker, @@ -68,15 +65,18 @@ class TestTransferDialog(unittest.TestCase, QuamashTest): None) self.account.wallets[0].init_cache(self.application, self.community) - async def open_dialog(certification_dialog): - result = await certification_dialog.async_exec() + async def open_dialog(transfer_dialog): + srv, port, url = await mock.create_server() + self.endpoint.port = port + + result = await transfer_dialog.async_exec() self.assertEqual(result, QDialog.Accepted) def close_dialog(): if transfer_dialog.isVisible(): transfer_dialog.close() - async def exec_test(): + async def exec_test(): await asyncio.sleep(1) self.account.wallets[0].caches[self.community.currency].available_sources = await self.wallet.sources(self.community) QTest.mouseClick(transfer_dialog.radio_pubkey, Qt.LeftButton) @@ -92,7 +92,6 @@ class TestTransferDialog(unittest.TestCase, QuamashTest): self.lp.call_later(15, close_dialog) asyncio.ensure_future(exec_test()) self.lp.run_until_complete(open_dialog(transfer_dialog)) - mock.delete_mock() if __name__ == '__main__': diff --git a/src/sakia/tests/core/__init__.py b/src/sakia/tests/functional/wot_tab/__init__.py similarity index 100% rename from src/sakia/tests/core/__init__.py rename to src/sakia/tests/functional/wot_tab/__init__.py diff --git a/src/sakia/tests/gui/wot_tab/test_wot_tab.py b/src/sakia/tests/functional/wot_tab/test_wot_tab.py similarity index 88% rename from src/sakia/tests/gui/wot_tab/test_wot_tab.py rename to src/sakia/tests/functional/wot_tab/test_wot_tab.py index 08e97cbf9d68126140b80baf80226b7e3c128d68..47996c5798e8d5c8563553dcfed96007df60a85f 100644 --- a/src/sakia/tests/gui/wot_tab/test_wot_tab.py +++ b/src/sakia/tests/functional/wot_tab/test_wot_tab.py @@ -10,7 +10,7 @@ from PyQt5.QtCore import QLocale, Qt from PyQt5.QtTest import QTest from ucoinpy.api import bma from ucoinpy.api.bma import API -from sakia.tests.mocks.monkeypatch import pretender_reversed + from sakia.tests.mocks.bma import nice_blockchain from sakia.core.registry.identities import IdentitiesRegistry from sakia.gui.wot_tab import WotTabWidget @@ -31,7 +31,7 @@ class TestWotTab(unittest.TestCase, QuamashTest): self.application = Application(self.qapplication, self.lp, self.identities_registry) self.application.preferences['notifications'] = False - self.endpoint = BMAEndpoint("", "127.0.0.1", "", 50000) + self.endpoint = BMAEndpoint("", "127.0.0.1", "", 50003) self.node = Node("test_currency", [self.endpoint], "", "HnFcSms8jzwngtVomTTnzudZx7SHUQY8sVE1y8yBmULk", None, Node.ONLINE, @@ -56,10 +56,8 @@ class TestWotTab(unittest.TestCase, QuamashTest): self.tearDownQuamash() def test_empty_wot_tab(self): - mock = nice_blockchain.get_mock() + mock = nice_blockchain.get_mock(self.lp) time.sleep(2) - logging.debug(mock.pretend_url) - API.reverse_url = pretender_reversed(mock.pretend_url) wot_tab = WotTabWidget(self.application) future = asyncio.Future() @@ -67,7 +65,9 @@ class TestWotTab(unittest.TestCase, QuamashTest): wot_tab.show() return future - async def async_open_widget(): + async def async_open_widget(): + srv, port, url = await mock.create_server() + self.endpoint.port = port await open_widget() def close_dialog(): @@ -75,7 +75,7 @@ class TestWotTab(unittest.TestCase, QuamashTest): wot_tab.close() future.set_result(True) - async def exec_test(): + async def exec_test(): await asyncio.sleep(1) self.assertTrue(wot_tab.isVisible()) self.lp.call_soon(close_dialog) @@ -83,7 +83,6 @@ class TestWotTab(unittest.TestCase, QuamashTest): asyncio.ensure_future(exec_test()) self.lp.call_later(15, close_dialog) self.lp.run_until_complete(async_open_widget()) - mock.delete_mock() if __name__ == '__main__': logging.basicConfig( stream=sys.stderr ) diff --git a/src/sakia/tests/gui/wot_tab/__init__.py b/src/sakia/tests/gui/wot_tab/__init__.py deleted file mode 100644 index 39ab2a0b56350baad834cb7fb0cfecb8223e1fcd..0000000000000000000000000000000000000000 --- a/src/sakia/tests/gui/wot_tab/__init__.py +++ /dev/null @@ -1 +0,0 @@ -__author__ = 'inso' diff --git a/src/sakia/tests/mocks/__init__.py b/src/sakia/tests/mocks/__init__.py index 7e4cdeb7cb59ef2876f24361d303fcc281ec4ef8..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 100644 --- a/src/sakia/tests/mocks/__init__.py +++ b/src/sakia/tests/mocks/__init__.py @@ -1 +0,0 @@ -__author__ = 'ggoinvic' diff --git a/src/sakia/tests/mocks/bma/corrupted.py b/src/sakia/tests/mocks/bma/corrupted.py index 3991a9aff47815e205e8727fc4ae35a9d9ee51bc..a147e884635086bb3ded3ee2f3d76008c4939b9f 100644 --- a/src/sakia/tests/mocks/bma/corrupted.py +++ b/src/sakia/tests/mocks/bma/corrupted.py @@ -1,7 +1,5 @@ import json -import time -from pretenders.client.http import HTTPMock -from pretenders.common.constants import FOREVER +from ..server import MockServer bma_memberships_empty_array = { "pubkey": "7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ", @@ -23,12 +21,9 @@ bma_null_data = { ] } -def get_mock(): - mock = HTTPMock('127.0.0.1', 50000) +def get_mock(loop): + mock = MockServer(loop) - mock.when('GET /blockchain/memberships/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ')\ - .reply(body=bytes(json.dumps(bma_memberships_empty_array), "utf-8"), - times=FOREVER, - headers={'Content-Type': 'application/json'}) + mock.add_route('GET', '/blockchain/memberships/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ', bma_memberships_empty_array) return mock diff --git a/src/sakia/tests/mocks/bma/init_new_community.py b/src/sakia/tests/mocks/bma/init_new_community.py index cb4700e37e42d8ef03668902e64cf690dd8ae5a6..8166fd95ec7e238b845900c67f501cc5de895e1c 100644 --- a/src/sakia/tests/mocks/bma/init_new_community.py +++ b/src/sakia/tests/mocks/bma/init_new_community.py @@ -1,21 +1,9 @@ -from pretenders.client.http import HTTPMock -from pretenders.common.constants import FOREVER - -bma_peering = b"""{ - "version": 1, - "currency": "test_currency", - "endpoints": [ - "BASIC_MERKLED_API localhost 127.0.0.1 50000" - ], - "status": "UP", - "block": "30152-00003E7F9234E7542FCF669B69B0F84FF79CCCD3", - "signature": "cXuqZuDfyHvxYAEUkPH1TQ1M+8YNDpj8kiHGYi3LIaMqEdVqwVc4yQYGivjxFMYyngRfxXkyvqBKZA6rKOulCA==", - "raw": "Version: 1\\nType: Peer\\nCurrency: meta_brouzouf\\nPublicKey: HnFcSms8jzwngtVomTTnzudZx7SHUQY8sVE1y8yBmULk\\nBlock: 30152-00003E7F9234E7542FCF669B69B0F84FF79CCCD3\\nEndpoints:\\nBASIC_MERKLED_API localhost 127.0.0.1 50000\\n", - "pubkey": "HnFcSms8jzwngtVomTTnzudZx7SHUQY8sVE1y8yBmULk" -}""" - -bma_lookup_test_john = b"""{ - "partial": false, + +from ..server import MockServer + + +bma_lookup_test_john = { + "partial": False, "results": [ { "pubkey": "7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ", @@ -32,10 +20,10 @@ bma_lookup_test_john = b"""{ "signed": [] } ] -}""" +} -bma_lookup_test_doe = b"""{ - "partial": false, +bma_lookup_test_doe = { + "partial": False, "results": [ { "pubkey": "FADxcH5LmXGmGFgdixSes6nWnC4Vb4pRUBYT81zQRhjn", @@ -52,10 +40,10 @@ bma_lookup_test_doe = b"""{ "signed": [] } ] -}""" +} -bma_lookup_test_patrick = b"""{ - "partial": false, +bma_lookup_test_patrick = { + "partial": False, "results": [ { "pubkey": "FADxcH5LmXGmGFgdixSes6nWnC4Vb4pRUBYT81zQRhjn", @@ -72,75 +60,31 @@ bma_lookup_test_patrick = b"""{ "signed": [] } ] -}""" - - -def get_mock(): - mock = HTTPMock('127.0.0.1', 50000) - - mock.when('GET /network/peering')\ - .reply(body=bma_peering, - times=FOREVER, - headers={'Content-Type': 'application/json'}) - - mock.when('GET /blockchain/block/0')\ - .reply(body=b"Block not found", - status=404, - times=FOREVER, - headers={'Content-Type': 'application/json'}) - - mock.when('GET /blockchain/current')\ - .reply(body=b"Block not found", - status=404, - times=FOREVER, - headers={'Content-Type': 'application/json'}) - - mock.when('GET /wot/certifiers-of/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ')\ - .reply(body=b"No member matching this pubkey or uid", - status=404, - times=1, - headers={'Content-Type': 'application/json'}) - - mock.when('GET /wot/lookup/john')\ - .reply(body=bma_lookup_test_john, - status=200, - times=1, - headers={'Content-Type': 'application/json'}) - - mock.when('GET /wot/lookup/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ')\ - .reply(body=bma_lookup_test_john, - status=200, - times=1, - headers={'Content-Type': 'application/json'}) - - mock.when('GET /wot/lookup/doe')\ - .reply(body=bma_lookup_test_doe, - status=200, - times=1, - headers={'Content-Type': 'application/json'}) - - mock.when('GET /wot/lookup/FADxcH5LmXGmGFgdixSes6nWnC4Vb4pRUBYT81zQRhjn')\ - .reply(body=bma_lookup_test_doe, - status=200, - times=1, - headers={'Content-Type': 'application/json'}) - - mock.when('GET /wot/lookup/patrick')\ - .reply(body=bma_lookup_test_patrick, - status=200, - times=1, - headers={'Content-Type': 'application/json'}) - - mock.when('GET /wot/lookup/FADxcH5LmXGmGFgdixSes6nWnC4Vb4pRUBYT81zQRhjn')\ - .reply(body=bma_lookup_test_patrick, - status=200, - times=1, - headers={'Content-Type': 'application/json'}) - - mock.when('POST /wot/add.*')\ - .reply(body=b"{}", - status=200, - times=FOREVER, - headers={'Content-Type': 'application/json'}) +} + + +def get_mock(loop): + mock = MockServer(loop) + + mock.add_route('GET', '/blockchain/block/0', {"message": "Block not found"}, 404) + + mock.add_route('GET', '/blockchain/current', {'message': "Block not found"}, 404) + + mock.add_route('GET', '/wot/certifiers-of/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ', + {'message': "No member matching this pubkey or uid"}, 404) + + mock.add_route('GET', '/wot/lookup/john', bma_lookup_test_john, 200) + + mock.add_route('GET', '/wot/lookup/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ', bma_lookup_test_john, 200) + + mock.add_route('GET', '/wot/lookup/doe', bma_lookup_test_doe, 200) + + mock.add_route('GET', '/wot/lookup/FADxcH5LmXGmGFgdixSes6nWnC4Vb4pRUBYT81zQRhjn', bma_lookup_test_doe, 200) + + mock.add_route('GET', '/wot/lookup/patrick', bma_lookup_test_patrick, 200) + + mock.add_route('GET', '/wot/lookup/FADxcH5LmXGmGFgdixSes6nWnC4Vb4pRUBYT81zQRhjn', bma_lookup_test_patrick, 200) + + mock.add_route('POST', '/wot/add', {}, 200) return mock diff --git a/src/sakia/tests/mocks/bma/new_blockchain.py b/src/sakia/tests/mocks/bma/new_blockchain.py index fe43d5d23588847d02cb084c47eb42aa6c9f71de..fd73693ebf41b6ed2700f2e1d215c878a7667367 100644 --- a/src/sakia/tests/mocks/bma/new_blockchain.py +++ b/src/sakia/tests/mocks/bma/new_blockchain.py @@ -1,20 +1,7 @@ -from pretenders.client.http import HTTPMock -from pretenders.common.constants import FOREVER +from ..server import MockServer -bma_peering = b"""{ - "version": 1, - "currency": "test_currency", - "endpoints": [ - "BASIC_MERKLED_API localhost 127.0.0.1 50000" - ], - "status": "UP", - "block": "30152-00003E7F9234E7542FCF669B69B0F84FF79CCCD3", - "signature": "cXuqZuDfyHvxYAEUkPH1TQ1M+8YNDpj8kiHGYi3LIaMqEdVqwVc4yQYGivjxFMYyngRfxXkyvqBKZA6rKOulCA==", - "raw": "Version: 1\\nType: Peer\\nCurrency: meta_brouzouf\\nPublicKey: HnFcSms8jzwngtVomTTnzudZx7SHUQY8sVE1y8yBmULk\\nBlock: 30152-00003E7F9234E7542FCF669B69B0F84FF79CCCD3\\nEndpoints:\\nBASIC_MERKLED_API localhost 127.0.0.1 50000\\n", - "pubkey": "HnFcSms8jzwngtVomTTnzudZx7SHUQY8sVE1y8yBmULk" -}""" -bma_wot_add = b"""{ +bma_wot_add = { "pubkey": "7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ", "uids": [ { @@ -27,43 +14,26 @@ bma_wot_add = b"""{ ] } ] -}""" +} -def get_mock(): - mock = HTTPMock('127.0.0.1', 50000) +def get_mock(loop): + mock = MockServer(loop) - mock.when('GET /network/peering')\ - .reply(body=bma_peering, - times=FOREVER, - headers={'Content-Type': 'application/json'}) + mock.add_route('GET', '/blockchain/block/0', {'message': "Block not found"}, 404) - mock.when('GET /blockchain/block/0')\ - .reply(body=b"Block not found", - status=404, - times=FOREVER, - headers={'Content-Type': 'application/json'}) + mock.add_route('GET', '/blockchain/current', {'message': "Block not found"}, 404) - mock.when('GET /blockchain/current')\ - .reply(body=b"Block not found", - status=404, - times=FOREVER, - headers={'Content-Type': 'application/json'}) + mock.add_route('GET', '/wot/certifiers-of/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ', + {'message': "No member matching this pubkey or uid"}, 404) - mock.when('GET /wot/certifiers-of/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ')\ - .reply(body=b"No member matching this pubkey or uid", - status=404, - times=1, - headers={'Content-Type': 'application/json'}) + mock.add_route('GET', '/wot/lookup/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ', + {'message': "No member matching this pubkey or uid"}, 404) - mock.when('GET /wot/lookup/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ')\ - .reply(body=b"No member matching this pubkey or uid", - status=404, - times=1, - headers={'Content-Type': 'application/json'}) + mock.add_route('GET', '/wot/lookup/john', + {'message': "No member matching this pubkey or uid"}, 404) - mock.when('POST /wot/add.*')\ - .reply(body=bma_wot_add, - status=200, - times=FOREVER, - headers={'Content-Type': 'application/json'}) + mock.add_route('GET', '/wot/lookup/doe', + {'message': "No member matching this pubkey or uid"}, 404) + + mock.add_route('POST', '/wot/add', bma_wot_add, 200) return mock diff --git a/src/sakia/tests/mocks/bma/nice_blockchain.py b/src/sakia/tests/mocks/bma/nice_blockchain.py index f60b6716be3d00fff7896ba096d079f43090b976..2029188cd127134d62179b0a4aa6dfaba9efc82f 100644 --- a/src/sakia/tests/mocks/bma/nice_blockchain.py +++ b/src/sakia/tests/mocks/bma/nice_blockchain.py @@ -1,20 +1,4 @@ -import json -import time -from pretenders.client.http import HTTPMock -from pretenders.common.constants import FOREVER - -bma_peering = { - "version": 1, - "currency": "test_currency", - "endpoints": [ - "BASIC_MERKLED_API localhost 127.0.0.1 50000" - ], - "status": "UP", - "block": "30152-00003E7F9234E7542FCF669B69B0F84FF79CCCD3", - "signature": "cXuqZuDfyHvxYAEUkPH1TQ1M+8YNDpj8kiHGYi3LIaMqEdVqwVc4yQYGivjxFMYyngRfxXkyvqBKZA6rKOulCA==", - "raw": "Version: 1\nType: Peer\nCurrency: meta_brouzouf\nPublicKey: HnFcSms8jzwngtVomTTnzudZx7SHUQY8sVE1y8yBmULk\nBlock: 30152-00003E7F9234E7542FCF669B69B0F84FF79CCCD3\nEndpoints:\nBASIC_MERKLED_API localhost 127.0.0.1 50000\n", - "pubkey": "HnFcSms8jzwngtVomTTnzudZx7SHUQY8sVE1y8yBmULk" -} +from ..server import MockServer bma_lookup_john = { "partial": False, @@ -356,120 +340,45 @@ bma_with_ud = { } -def get_mock(): - mock = HTTPMock('127.0.0.1', 50000) - - mock.when('GET /network/peering') \ - .reply(body=bytes(json.dumps(bma_peering), "utf-8"), - times=FOREVER, - headers={'Content-Type': 'application/json'}) - - mock.when('GET /blockchain/parameters') \ - .reply(body=bytes(json.dumps(bma_parameters), "utf-8"), - status=200, - times=FOREVER, - headers={'Content-Type': 'application/json'}) - - mock.when('GET /blockchain/with/[UD|ud]') \ - .reply(body=bytes(json.dumps(bma_with_ud), "utf-8"), - status=200, - times=FOREVER, - headers={'Content-Type': 'application/json'}) - - mock.when('GET /blockchain/current') \ - .reply(body=bytes(json.dumps(bma_blockchain_current), "utf-8"), - status=200, - times=FOREVER, - headers={'Content-Type': 'application/json'}) - - mock.when('GET /blockchain/block/0') \ - .reply(body=bytes(json.dumps(bma_blockchain_0), "utf-8"), - status=200, - times=FOREVER, - headers={'Content-Type': 'application/json'}) - - mock.when('GET /blockchain/block/15') \ - .reply(body=bytes(json.dumps(bma_blockchain_current), "utf-8"), - status=200, - times=FOREVER, - headers={'Content-Type': 'application/json'}) - - mock.when('GET /tx/history/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ/blocks/0/99') \ - .reply(body=bytes(json.dumps(bma_txhistory_john), "utf-8"), - status=200, - times=FOREVER, - headers={'Content-Type': 'application/json'}) - - mock.when('GET /tx/sources/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ') \ - .reply(body=bytes(json.dumps(bma_txsources_john), "utf-8"), - status=200, - times=FOREVER, - headers={'Content-Type': 'application/json'}) - - mock.when('GET /ud/history/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ') \ - .reply(body=bytes(json.dumps(bma_udhistory_john), "utf-8"), - status=200, - times=FOREVER, - headers={'Content-Type': 'application/json'}) - - mock.when('GET /wot/certifiers-of/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ') \ - .reply(body=bytes(json.dumps(bma_certifiers_of_john), "utf-8"), - status=200, - times=FOREVER, - headers={'Content-Type': 'application/json'}) - - mock.when('GET /wot/certified-by/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ') \ - .reply(body=bytes(json.dumps(bma_certified_by_john), "utf-8"), - status=200, - times=FOREVER, - headers={'Content-Type': 'application/json'}) - - mock.when('GET /wot/lookup/john') \ - .reply(body=bytes(json.dumps(bma_lookup_john), "utf-8"), - status=200, - times=FOREVER, - headers={'Content-Type': 'application/json'}) - - mock.when('GET /wot/lookup/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ') \ - .reply(body=bytes(json.dumps(bma_lookup_john), "utf-8"), - status=200, - times=FOREVER, - headers={'Content-Type': 'application/json'}) - - mock.when('GET /wot/lookup/doe') \ - .reply(body=bytes(json.dumps(bma_lookup_doe), "utf-8"), - status=200, - times=1, - headers={'Content-Type': 'application/json'}) - - mock.when('GET /wot/lookup/FADxcH5LmXGmGFgdixSes6nWnC4Vb4pRUBYT81zQRhjn') \ - .reply(body=bytes(json.dumps(bma_lookup_doe), "utf-8"), - status=200, - times=FOREVER, - headers={'Content-Type': 'application/json'}) - - mock.when('GET /blockchain/memberships/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ') \ - .reply(body=bytes(json.dumps(bma_membership_john), "utf-8"), - status=200, - times=FOREVER, - headers={'Content-Type': 'application/json'}) - - mock.when('GET /wot/certifiers-of/FADxcH5LmXGmGFgdixSes6nWnC4Vb4pRUBYT81zQRhjn') \ - .reply(body=b"No member matching this pubkey or uid", - status=404, - times=FOREVER, - headers={'Content-Type': 'application/json'}) - - mock.when('GET /blockchain/memberships/FADxcH5LmXGmGFgdixSes6nWnC4Vb4pRUBYT81zQRhjn') \ - .reply(body=b"No member matching this pubkey or uid", - status=404, - times=FOREVER, - headers={'Content-Type': 'application/json'}) - - mock.when('POST /tx/process') \ - .reply(body=b"", - status=200, - times=FOREVER, - headers={'Content-Type': 'application/json'}) +def get_mock(loop): + mock = MockServer(loop) + + mock.add_route('GET', '/blockchain/parameters', bma_parameters, 200) + + mock.add_route('GET', '/blockchain/with/[UD|ud]', bma_with_ud, 200) + + mock.add_route('GET', '/blockchain/current', bma_blockchain_current, 200) + + mock.add_route('GET', '/blockchain/block/0', bma_blockchain_0, 200) + + mock.add_route('GET', '/blockchain/block/15', bma_blockchain_current, 200) + + mock.add_route('GET', '/tx/history/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ/blocks/0/99', bma_txhistory_john, 200) + + mock.add_route('GET', '/tx/sources/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ', bma_txsources_john, 200) + + mock.add_route('GET', '/ud/history/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ', bma_udhistory_john, 200) + + mock.add_route('GET', '/wot/certifiers-of/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ', bma_certifiers_of_john, 200) + + mock.add_route('GET', '/wot/certified-by/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ', bma_certified_by_john, 200) + + mock.add_route('GET', '/wot/lookup/john', bma_lookup_john, 200) + + mock.add_route('GET', '/wot/lookup/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ', bma_lookup_john, 200) + + mock.add_route('GET', '/wot/lookup/doe', bma_lookup_doe, 200) + + mock.add_route('GET', '/wot/lookup/FADxcH5LmXGmGFgdixSes6nWnC4Vb4pRUBYT81zQRhjn',bma_lookup_doe,200) + + mock.add_route('GET', '/blockchain/memberships/7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ',bma_membership_john,200) + + mock.add_route('GET', '/wot/certifiers-of/FADxcH5LmXGmGFgdixSes6nWnC4Vb4pRUBYT81zQRhjn', + {'error':"No member matching this pubkey or uid"},404) + + mock.add_route('GET', '/blockchain/memberships/FADxcH5LmXGmGFgdixSes6nWnC4Vb4pRUBYT81zQRhjn', + {'error':"No member matching this pubkey or uid"}, 404) + + mock.add_route('POST', '/tx/process', {},200,) return mock diff --git a/src/sakia/tests/mocks/monkeypatch.py b/src/sakia/tests/mocks/monkeypatch.py deleted file mode 100644 index 7df5878d5afe777a1b88e2924eb8a5508d984ca3..0000000000000000000000000000000000000000 --- a/src/sakia/tests/mocks/monkeypatch.py +++ /dev/null @@ -1,16 +0,0 @@ - - -def pretender_reversed(pretender_id): - def reverse_url(inst, path): - """ - Reverses the url using self.url and path given in parameter. - - Arguments: - - `path`: the request path - """ - - server, port = inst.connection_handler.server, inst.connection_handler.port - - url = '%s/%s' % (pretender_id, inst.module) - return url + path - return reverse_url \ No newline at end of file diff --git a/src/sakia/tests/mocks/server.py b/src/sakia/tests/mocks/server.py new file mode 100644 index 0000000000000000000000000000000000000000..9e25711c363f9b50497bae949bfe3de438c84efa --- /dev/null +++ b/src/sakia/tests/mocks/server.py @@ -0,0 +1,67 @@ +from aiohttp import web, log +import json +import socket + + +def bma_peering_generator(port): + return { + "version": 1, + "currency": "test_currency", + "endpoints": [ + "BASIC_MERKLED_API localhost 127.0.0.1 {port}".format(port=port) + ], + "status": "UP", + "block": "30152-00003E7F9234E7542FCF669B69B0F84FF79CCCD3", + "signature": "cXuqZuDfyHvxYAEUkPH1TQ1M+8YNDpj8kiHGYi3LIaMqEdVqwVc4yQYGivjxFMYyngRfxXkyvqBKZA6rKOulCA==", + "raw": "Version: 1\nType: Peer\nCurrency: meta_brouzouf\nPublicKey: HnFcSms8jzwngtVomTTnzudZx7SHUQY8sVE1y8yBmULk\nBlock: 30152-00003E7F9234E7542FCF669B69B0F84FF79CCCD3\nEndpoints:\nBASIC_MERKLED_API localhost 127.0.0.1 {port}\n".format(port=port), + "pubkey": "HnFcSms8jzwngtVomTTnzudZx7SHUQY8sVE1y8yBmULk" + } + + +class Request(): + def __init__(self, method, url, content): + self.url = url + self.method = method + self.content = content + + +class MockServer(): + def __init__(self, loop): + self.lp = loop + self.requests = [] + self.app = web.Application(loop=self.lp) + + self.handler = self.app.make_handler( + keep_alive_on=False, + access_log=log.access_logger) + + def get_request(self, i): + return self.requests[i] + + async def _handler(self, request, data_dict, http_code): + await request.read() + self.requests.append(Request(request.method, request.path, request.content)) + return web.Response(body=bytes(json.dumps(data_dict), "utf-8"), + headers={'Content-Type': 'application/json'}, + status=http_code) + + def add_route(self, req_type, url, data_dict, http_code=200): + self.app.router.add_route(req_type, url, + lambda request: self._handler(request, data_dict=data_dict, http_code=http_code)) + + def find_unused_port(self): + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.bind(('127.0.0.1', 0)) + port = s.getsockname()[1] + s.close() + return port + + async def create_server(self, ssl_ctx=None): + port = self.find_unused_port() + srv = await self.lp.create_server(self.handler, '127.0.0.1', port) + protocol = "https" if ssl_ctx else "http" + url = "{}://127.0.0.1:{}".format(protocol, port) + + self.add_route('GET', '/network/peering', bma_peering_generator(port)) + + return srv, port, url \ No newline at end of file diff --git a/src/sakia/tests/quamash_test.py b/src/sakia/tests/quamash_utils.py similarity index 84% rename from src/sakia/tests/quamash_test.py rename to src/sakia/tests/quamash_utils.py index 09d5d10773f8bd208d281bbc0c844fa545d67fd8..ae7610528fbec45516a6238d4dca54d9fdd28a99 100644 --- a/src/sakia/tests/quamash_test.py +++ b/src/sakia/tests/quamash_utils.py @@ -1,5 +1,7 @@ import asyncio import quamash +import socket +from aiohttp import web, log _application_ = [] @@ -11,12 +13,14 @@ class QuamashTest: asyncio.set_event_loop(self.lp) self.lp.set_exception_handler(lambda l, c: unitttest_exception_handler(self, l, c)) self.exceptions = [] + self.handler = None def tearDownQuamash(self): try: self.lp.close() finally: asyncio.set_event_loop(None) + for exc in self.exceptions: raise exc @@ -28,7 +32,10 @@ def unitttest_exception_handler(test, loop, context): :param loop: the asyncio loop :param context: the exception context """ - exception = context['exception'] + if 'exception' in context: + exception = context['exception'] + else: + exception = BaseException(context['message']) test.exceptions.append(exception) diff --git a/src/sakia/tests/unit/__init__.py b/src/sakia/tests/unit/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/src/sakia/tests/core/txhistory/__init__.py b/src/sakia/tests/unit/core/__init__.py similarity index 100% rename from src/sakia/tests/core/txhistory/__init__.py rename to src/sakia/tests/unit/core/__init__.py diff --git a/src/sakia/tests/core/test_account.py b/src/sakia/tests/unit/core/test_account.py similarity index 100% rename from src/sakia/tests/core/test_account.py rename to src/sakia/tests/unit/core/test_account.py diff --git a/src/sakia/tests/core/test_bma_access.py b/src/sakia/tests/unit/core/test_bma_access.py similarity index 93% rename from src/sakia/tests/core/test_bma_access.py rename to src/sakia/tests/unit/core/test_bma_access.py index 094c0686648241de67e616afa76244059bf35f2b..6708d6937410b5c4b17add6a912321631e6f9890 100644 --- a/src/sakia/tests/core/test_bma_access.py +++ b/src/sakia/tests/unit/core/test_bma_access.py @@ -6,7 +6,7 @@ import logging import time from PyQt5.QtCore import QLocale from sakia.core.registry.identities import Identity, IdentitiesRegistry, LocalState, BlockchainState -from sakia.tests.mocks.monkeypatch import pretender_reversed + from sakia.tests.mocks.bma import nice_blockchain, corrupted from sakia.tests import QuamashTest from sakia.core import Application, Community @@ -26,7 +26,7 @@ class TestBmaAccess(unittest.TestCase, QuamashTest): self.application = Application(self.qapplication, self.lp, self.identities_registry) self.application.preferences['notifications'] = False - self.endpoint = BMAEndpoint("", "127.0.0.1", "", 50000) + self.endpoint = BMAEndpoint("", "127.0.0.1", "", 50004) self.node = Node("test_currency", [self.endpoint], "", "HnFcSms8jzwngtVomTTnzudZx7SHUQY8sVE1y8yBmULk", None, Node.ONLINE, diff --git a/src/sakia/tests/core/test_community.py b/src/sakia/tests/unit/core/test_community.py similarity index 100% rename from src/sakia/tests/core/test_community.py rename to src/sakia/tests/unit/core/test_community.py diff --git a/src/sakia/tests/core/test_identities.py b/src/sakia/tests/unit/core/test_identities.py similarity index 100% rename from src/sakia/tests/core/test_identities.py rename to src/sakia/tests/unit/core/test_identities.py diff --git a/src/sakia/tests/core/test_identity.py b/src/sakia/tests/unit/core/test_identity.py similarity index 73% rename from src/sakia/tests/core/test_identity.py rename to src/sakia/tests/unit/core/test_identity.py index dac636724a58654f678fbf40c57fadbb5157a6d1..ed8c95b83f006a84255f62456073c9b40083c21d 100644 --- a/src/sakia/tests/core/test_identity.py +++ b/src/sakia/tests/unit/core/test_identity.py @@ -1,12 +1,13 @@ import sys import unittest -import asyncio -import quamash import logging import time +import asyncio +import json +from aiohttp import web from PyQt5.QtCore import QLocale from sakia.core.registry.identities import Identity, IdentitiesRegistry, LocalState, BlockchainState -from sakia.tests.mocks.monkeypatch import pretender_reversed + from sakia.tests.mocks.bma import nice_blockchain, corrupted from sakia.tests import QuamashTest from sakia.core import Application, Community @@ -26,7 +27,7 @@ class TestIdentity(unittest.TestCase, QuamashTest): self.application = Application(self.qapplication, self.lp, self.identities_registry) self.application.preferences['notifications'] = False - self.endpoint = BMAEndpoint("", "127.0.0.1", "", 50000) + self.endpoint = BMAEndpoint("", "127.0.0.1", "", 50009) self.node = Node("test_currency", [self.endpoint], "", "HnFcSms8jzwngtVomTTnzudZx7SHUQY8sVE1y8yBmULk", None, Node.ONLINE, @@ -38,31 +39,33 @@ class TestIdentity(unittest.TestCase, QuamashTest): def tearDown(self): self.tearDownQuamash() - def test_identity_certified_by(self): - mock = nice_blockchain.get_mock() - time.sleep(2) - logging.debug(mock.pretend_url) - API.reverse_url = pretender_reversed(mock.pretend_url) + def test_identity_certifiers_of(self): + mock = nice_blockchain.get_mock(self.lp) + identity = Identity("john", "7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ", 1441130831, LocalState.COMPLETED, BlockchainState.VALIDATED) - async def exec_test(): - certified = await identity.certifiers_of(self.identities_registry, self.community) - self.assertEqual(len(certified), 1) - self.assertEqual(certified[0]['identity'].uid, "doe") + async def exec_test(): + srv, port, url = await mock.create_server() + self.endpoint.port = port + certifiers = await identity.certifiers_of(self.identities_registry, self.community) + + self.assertEqual(len(certifiers), 1) + self.assertEqual(certifiers[0]['identity'].uid, "doe") + # Force one more loop turn + await asyncio.sleep(0) self.lp.run_until_complete(exec_test()) - mock.delete_mock() def test_identity_membership(self): - mock = nice_blockchain.get_mock() + mock = nice_blockchain.get_mock(self.lp) time.sleep(2) - logging.debug(mock.pretend_url) - API.reverse_url = pretender_reversed(mock.pretend_url) identity = Identity("john", "7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ", 1441130831, LocalState.COMPLETED, BlockchainState.VALIDATED) - async def exec_test(): + async def exec_test(): + srv, port, url = await mock.create_server() + self.endpoint.port = port ms = await identity.membership(self.community) self.assertEqual(ms["blockNumber"], 0) self.assertEqual(ms["blockHash"], "DA39A3EE5E6B4B0D3255BFEF95601890AFD80709") @@ -70,22 +73,20 @@ class TestIdentity(unittest.TestCase, QuamashTest): self.assertEqual(ms["currency"], "test_currency") self.lp.run_until_complete(exec_test()) - mock.delete_mock() def test_identity_corrupted_membership(self): - mock = corrupted.get_mock() + mock = corrupted.get_mock(self.lp) time.sleep(2) - logging.debug(mock.pretend_url) - API.reverse_url = pretender_reversed(mock.pretend_url) identity = Identity("john", "7Aqw6Efa9EzE7gtsc8SveLLrM7gm6NEGoywSv4FJx6pZ", 1441130831, LocalState.COMPLETED, BlockchainState.VALIDATED) - async def exec_test(): + async def exec_test(): + srv, port, url = await mock.create_server() + self.endpoint.port = port with self.assertRaises(MembershipNotFoundError): await identity.membership(self.community) self.lp.run_until_complete(exec_test()) - mock.delete_mock() if __name__ == '__main__': diff --git a/src/sakia/tests/core/test_wallet.py b/src/sakia/tests/unit/core/test_wallet.py similarity index 100% rename from src/sakia/tests/core/test_wallet.py rename to src/sakia/tests/unit/core/test_wallet.py diff --git a/src/sakia/tests/gui/__init__.py b/src/sakia/tests/unit/core/txhistory/__init__.py similarity index 100% rename from src/sakia/tests/gui/__init__.py rename to src/sakia/tests/unit/core/txhistory/__init__.py diff --git a/src/sakia/tests/core/txhistory/test_txhistory_loading.py b/src/sakia/tests/unit/core/txhistory/test_txhistory_loading.py similarity index 95% rename from src/sakia/tests/core/txhistory/test_txhistory_loading.py rename to src/sakia/tests/unit/core/txhistory/test_txhistory_loading.py index 17f9c3a7764b1b11bdc70defb857fd3c7b5a3903..8c106b46eebd4e4bc4fbbf53b67bcb4fa28cd2af 100644 --- a/src/sakia/tests/core/txhistory/test_txhistory_loading.py +++ b/src/sakia/tests/unit/core/txhistory/test_txhistory_loading.py @@ -4,7 +4,6 @@ import asyncio import quamash import time import logging -from ucoinpy.documents.peer import BMAEndpoint as PyBMAEndpoint from PyQt5.QtCore import QLocale, Qt from sakia.tests.mocks.bma import nice_blockchain from sakia.core.registry.identities import IdentitiesRegistry @@ -25,7 +24,7 @@ class TestTxHistory(unittest.TestCase, QuamashTest): self.application = Application(self.qapplication, self.lp, self.identities_registry) self.application.preferences['notifications'] = False - self.endpoint = BMAEndpoint(PyBMAEndpoint("", "127.0.0.1", "", 50000)) + self.endpoint = BMAEndpoint("", "127.0.0.1", "", 50005) self.node = Node("test_currency", [self.endpoint], "", "HnFcSms8jzwngtVomTTnzudZx7SHUQY8sVE1y8yBmULk", nice_blockchain.bma_blockchain_current, Node.ONLINE,