예제 #1
0
    def test_make_move_column_full(self, mock_prompt, mock_display,
                                   mock_patch):
        """Assert user is informed if column is full and is re-prompted."""
        retry_prompt = 'Column 2 is full, please try another: '
        # mock response from server, column is full
        mock_body = {"message": retry_prompt}
        mock_response = Mock(status_code=400, json=lambda: mock_body)
        mock_patch.side_effect = [mock_response, Mock(status_code=200)]

        test_client = client.Client("lola", "789")
        test_client.make_move()
        first_promt = "It's your turn lola, please enter column (1 - 9): "
        expected_prompts = [
            call(first_promt),
            call(retry_prompt),
        ]
        self.assertListEqual(mock_prompt.call_args_list, expected_prompts)
        expected_url = "http://127.0.0.1/game/789"
        expected_calls = [
            call(expected_url, json={
                'column': 2,
                'name': 'lola'
            }),
            call(expected_url, json={
                'column': 3,
                'name': 'lola'
            })
        ]
        self.assertListEqual(mock_patch.call_args_list, expected_calls)
        mock_display.assert_called_once()
예제 #2
0
    def open_connection(self):
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)

        try:
            builtins.conn = client.Client(*self._args[0], **self._args[1])
        except ConnectionRefusedError:
            self.error_signal.emit(constants.ERR_NO_CONNECTION)
            return

        jugg.utils.reactive_event_loop(loop, conn.start(), conn.stop())
예제 #3
0
 def test_get_game_state_started_new_game(self, mock_sleep, mock_get):
     """Server responds it's waiting on a player to join game, wait."""
     mock_response_body = {
         "turn": None,
         "game_status": "playing",
         "board": board_fixture,
     }
     mock_response = Mock(json=lambda: mock_response_body)
     mock_get.return_value = mock_response
     test_client = client.Client("bar", "123")
     test_client.get_game_state()
     mock_get.assert_called_once_with('http://127.0.0.1/game/123')
     mock_sleep.assert_called_once_with(2)
예제 #4
0
 def test_get_game_state_your_turn(self, mock_move, mock_get):
     """Server responds it's this players turn, call make move."""
     mock_response_body = {
         "turn": "bar",
         "game_status": "playing",
         "board": board_fixture,
     }
     mock_response = Mock(json=lambda: mock_response_body)
     mock_get.return_value = mock_response
     test_client = client.Client("bar", "123")
     test_client.get_game_state()
     mock_get.assert_called_once_with('http://127.0.0.1/game/123')
     mock_move.assert_called_once_with()
예제 #5
0
 def test_get_game_state_game_won(self, mock_exit, mock_get):
     """Server responds game won, display board and exit game."""
     mock_response_body = {
         "turn": "foo",
         "game_status": "won",
         "board": board_fixture,
     }
     mock_response = Mock(json=lambda: mock_response_body)
     mock_get.return_value = mock_response
     test_client = client.Client("bar", "123")
     test_client.get_game_state()
     mock_get.assert_called_once_with('http://127.0.0.1/game/123')
     mock_exit.assert_called_once_with("Game over, foo has won.")
예제 #6
0
 def test_get_game_state_wait_for_turn(self, mock_sleep, mock_get):
     """Server responds it's the other player's turn, wait."""
     mock_response_body = {
         "turn": "foo",
         "game_status": "playing",
         "board": board_fixture,
     }
     mock_response = Mock(json=lambda: mock_response_body)
     mock_get.return_value = mock_response
     test_client = client.Client("bar", "123")
     test_client.get_game_state()
     mock_get.assert_called_once_with('http://127.0.0.1/game/123')
     mock_sleep.assert_called_once_with(2)
예제 #7
0
    def start(self):
        """
        This function starts the bot. It essentially does 3 things:
            1. Configures the logger
            2. Imports custom plugins (it passes an instance of the client to each plugin which enables access to chat
               bot features.
            3. Connects the bot to the slack api

        :return:
            none -- changes application state
        """
        self.log.info(app.SPLASH)
        self.log.info("Preparing plugins to import")

        self._prepare_custom_plugin_import()
        sys.path.append(abspath(app.RELATIVE_PLUGIN_DIRECTORY_PATH))

        self.log.info("Found {0} plugin candidates.".format(len(self.modules)))

        self._sanitize_plugin_list()

        self.log.info("{0} Plugin candidates after sanitization".format(
            len(self.modules)))

        self.log.info("initializing slack client")

        doddle = client.Client(
            os.environ.get(app.ENVIRONMENT_VARIABLE_BOT_ID),
            os.environ.get(app.ENVIRONMENT_VARIABLE_BOT_TOKEN),
            self.config_reader.read_config())

        self.log.info("Importing plugins...")

        for mod in self.modules:
            try:
                if not mod.__contains("init"):
                    path = list(sys.path)
                    str = mod.split("/")
                    sys.path.insert(0, str[0] + "/" + str[1])
                    self.imported_modules.append(
                        importlib.import_module(str[2][:-3]))
            finally:
                sys.path[:] = path

        for mod in self.imported_modules:
            self.log.info("Loading plugin: " + mod.__name__)
            obj = getattr(mod, mod.__name__)
            obj(doddle)

        doddle.start()
예제 #8
0
 def test_make_move_acceptable_move(self, mock_prompt, mock_display,
                                    mock_patch):
     mock_patch.return_value = Mock(status_code=200)
     test_client = client.Client("foo", "123")
     test_client.make_move()
     expected_message = "It's your turn foo, please enter column (1 - 9): "
     mock_prompt.assert_called_once_with(expected_message)
     expected_payload = {
         "name": "foo",
         "column": 1,
     }
     expected_url = "http://127.0.0.1/game/123"
     mock_patch.assert_called_once_with(expected_url, json=expected_payload)
     mock_display.assert_called_once()
예제 #9
0
 def test_get_game_state_game_disconnected(self, mock_exit, mock_get):
     """Server responds game disconnected, exit game."""
     mock_response_body = {
         "turn": "foo",
         "game_status": "disconnected",
         "board": board_fixture,
     }
     mock_response = Mock(json=lambda: mock_response_body)
     mock_get.return_value = mock_response
     test_client = client.Client("bar", "123")
     test_client.get_game_state()
     mock_get.assert_called_once_with('http://127.0.0.1/game/123')
     mock_exit.assert_called_once_with(
         "Game over, other player disconnected.")
예제 #10
0
 def test_make_move_invalid_column(self, mock_prompt, mock_display,
                                   mock_patch):
     """Assert the user is prompted until a valid column is chosen."""
     mock_patch.return_value = Mock(status_code=200)
     test_client = client.Client("bar", "456")
     test_client.make_move()
     first_promt = "It's your turn bar, please enter column (1 - 9): "
     retry_prompt = 'Invalid choice, please enter column (1 - 9): '
     expected_calls = [
         call(first_promt),
         call(retry_prompt),
         call(retry_prompt),
         call(retry_prompt),
         call(retry_prompt)
     ]
     self.assertListEqual(mock_prompt.call_args_list, expected_calls)
     expected_payload = {
         "name": "bar",
         "column": 9,
     }
     expected_url = "http://127.0.0.1/game/456"
     mock_patch.assert_called_once_with(expected_url, json=expected_payload)
     mock_display.assert_called_once()
예제 #11
0
def test_send_presence_msg():
    c = client.Client()
    c.connect_to_server('127.0.0.1', 7777)
    assert c.send_presence_msg()
예제 #12
0
def test_connect_to_server():
    c = client.Client()
    assert c.connect_to_server('127.0.0.1', 7777) is None
예제 #13
0
파일: run.py 프로젝트: XroixHD/RenameX
MIT License

Copyright (c) 2020 XroixHD

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from src import client, storage

if __name__ == '__main__':
    # Create storage beforehand
    storage = storage.Storage()

    client = client.Client(storage)
    client.run(storage["token"])
예제 #14
0
import datetime
from src import bank, account, client, account_updater

if __name__ == '__main__':

    banc1 = bank.Bank('Picpay', '19547148412')

    print(banc1)
    print(banc1._created_at)
    print(banc1.created_at)
    print(banc1.updated_at)
    print(datetime.datetime.now())

    cliente1 = client.Client('Caíque', 'Brandão', '10483042641', '15/09/1994')
    cliente2 = client.Client('Thainá', 'Brandão', '41970143843', '21/05/1995')
    cliente3 = client.Client('João', 'Brandão', '41970143843', '21/05/1995')

    #c = Conta('123-4', cliente1, 1000.0)
    cc1 = account.CurrentAccount(cliente1, 750.0)
    cc2 = account.CurrentAccount(cliente2, 1750.0)
    #cp = ContaPoupanca('123-6', cliente3, 1000.0)

    #cc.atualiza(0.2)
    #ci.atualiza(0.2)

    #banc1.adicionaConta(c)
    banc1.addAccount(cc1)
    banc1.addAccount(cc2)
    #banc1.adicionaConta(cp)
    #banc1.adicionaConta(c2)
    #banc1.adicionaConta(ci)
예제 #15
0
def test_receive_response_from_server():
    c = client.Client()
    c.connect_to_server('127.0.0.1', 7777)
    c.send_presence_msg()
    assert c.receive_response_from_server()
예제 #16
0
    else:
        print("Full Node 1 has not accepted post:'" + wrong_post + "' - This is the correct logic")


def test_server(serverFullNode):
    server_simple_insertion_and_reset(serverFullNode)  # Insert 3 posts, display the tree and reset it.
    server_demo_merkle_root(serverFullNode)
    server_demo_update_merkle_root(serverFullNode)
    server_demo_valid_data(serverFullNode)
    server_demo_not_valid_data(serverFullNode)
    new_server = server.Server()
    two_full_node_demo(serverFullNode, new_server)


def test_client_server(clientLightNode, serverFullNode):
    # Peer just added a new post
    first_message_hash = Encode.sha256("a")
    serverFullNode.mt.update_tree(first_message_hash)
    # client check validity of data within its own 'light merkle tree'
    print(str(clientLightNode.add_post(first_message_hash, serverFullNode.mt.get_merkle_root())))
    second_message_hash = Encode.sha256("b")
    serverFullNode.mt.update_tree(second_message_hash)
    print(str(clientLightNode.add_post(second_message_hash, serverFullNode.mt.get_merkle_root())))


if __name__ == '__main__':
    clientLightNode = client.Client()  # Light Node
    serverFullNode = server.Server()  # Full Node
    #test_server(serverFullNode)  # Test posts insertion within the server
    #test_client_server(clientLightNode, serverFullNode)  # Test the data validation logic between client and server
예제 #17
0
import asyncio
import jugg

from src import client

cl = client.Client('127.0.0.1', 1492)

jugg.utils.reactive_event_loop(asyncio.get_event_loop(),
                               cl.start(),
                               cl.stop(),
                               run_forever=False)