Exemplo n.º 1
0
def test_run_least_mock(m_text):
    """test run til finished with least mock."""
    # mocked value used on profile
    m_tts = 'xxxx'
    m_va_gender = 'female'
    # mocked value used on module
    with mock.patch('melissa.profile_loader.load_profile'):
        from melissa import profile
        profile.data = {
            'actions_db_file': ':memory:',
            'modules': 'melissa.actions',
            'tts': m_tts,
            'va_gender': m_va_gender,
        }
        with mock.patch('melissa.brain.getattr') \
                as m_getattr:
            # pre run
            from melissa import brain
            # run
            brain.query(m_text)
            # test
            if m_text == 'define define':
                val_pack = ('define_subject', 'define define')
            elif m_text == 'feeling':
                val_pack = ('undefined', '')
            else:
                val_pack = ('feeling_angry', 'feeling angry')
            err_msg = ("Unexpected mock's calls. "
                       "actual mock's call:\n{}".format('\n'.join(
                           map(repr, m_getattr.mock_calls))))
            assert len(m_getattr.mock_calls) == 2, err_msg
            assert m_getattr.mock_calls[1][1][0] == val_pack[1], err_msg
            assert m_getattr.mock_calls[0][1][1] == val_pack[0], err_msg
Exemplo n.º 2
0
def test_run_least_mock(m_text):
    """test run til finished with least mock."""
    # mocked value used on profile
    m_tts = 'xxxx'
    m_va_gender = 'female'
    # mocked value used on module
    with mock.patch('melissa.profile_loader.load_profile'):
        from melissa import profile
        profile.data = {
            'actions_db_file': ':memory:',
            'modules': 'melissa.actions',
            'tts': m_tts,
            'va_gender': m_va_gender,
        }
        with mock.patch('melissa.brain.getattr') \
                as m_getattr:
            # pre run
            from melissa import brain
            # run
            brain.query(m_text)
            # test
            if m_text == 'define define':
                val_pack = ('define_subject', 'define define')
            elif m_text == 'feeling':
                val_pack = ('undefined', '')
            else:
                val_pack = ('feeling_angry', 'feeling angry')
            err_msg = (
                "Unexpected mock's calls. "
                "actual mock's call:\n{}".format(
                    '\n'.join(map(repr, m_getattr.mock_calls))))
            assert len(m_getattr.mock_calls) == 2, err_msg
            assert m_getattr.mock_calls[1][1][0] == val_pack[1], err_msg
            assert m_getattr.mock_calls[0][1][1] == val_pack[0], err_msg
Exemplo n.º 3
0
def handle_json(json):
    speech_text = json['data']
    print('Melissa thinks you said: ' + speech_text)

    # emit('melissa replies', 'thank you')

    if speech_text is None:
        pass
    else:
        query(speech_text)
Exemplo n.º 4
0
def handle_json(json):
    speech_text = json['data']
    print('Melissa thinks you said: ' + speech_text)

    # emit('melissa replies', 'thank you')

    if speech_text is None:
        pass
    else:
        query(speech_text)
Exemplo n.º 5
0
 def test_simple_mock_input(self):
     """test run til finished with multiple mock."""
     mock_text = mock.Mock()
     with mock.patch(
             'melissa.profile_populator.profile_populator') as mock_pp:
         # preparation for creating temp file
         with mock.patch('melissa.actions_db.assemble_actions_db') \
                 as mock_acdb:
             with mock.patch('melissa.brain.actions_db') as mock_adb:
                 from melissa.brain import query
                 with pytest.raises(TypeError):
                     query(mock_text)
                 assert not mock_pp.called
                 assert not mock_acdb.called
                 assert not mock_adb.called
Exemplo n.º 6
0
def main():
    tts('Welcome ' + profile.data['name'] + ', how can I help you?')

    while True:
        if sys.platform == 'darwin':
            subprocess.call(['afplay', 'data/snowboy_resources/ding.wav'])
        elif sys.platform.startswith('linux') or sys.platform == 'win32':
            subprocess.call(['mpg123', 'data/snowboy_resources/ding.wav'])

        text = stt()

        if text is None:
            continue
        else:
            query(text)
Exemplo n.º 7
0
def main():
    data = load_profile(True)
    tts('Welcome ' + data['name'] +
        ', how can I help you?')

    while True:
        if sys.platform == 'darwin':
            subprocess.call(['afplay', 'data/snowboy_resources/ding.wav'])
        elif sys.platform.startswith('linux') or sys.platform == 'win32':
            subprocess.call(['mpg123', 'data/snowboy_resources/ding.wav'])

        text = stt()

        if text is None:
            continue
        else:
            query(text)
Exemplo n.º 8
0
def test_run_least_mock_and_working_test(m_text, fetchall_side_effect):
    """test run til finished with least mock until test work.

    this similar to test_run_least_mock function but
    add additional mock to make test working on full test.
    """
    # mocked value used on profile
    m_tts = 'xxxx'
    m_va_gender = 'female'
    # mocked value used on module
    with mock.patch('melissa.profile_loader.load_profile'):
        from melissa import profile
        profile.data = {
            'actions_db_file': ':memory:',
            'modules': 'melissa.actions',
            'tts': m_tts,
            'va_gender': m_va_gender,
        }
        with mock.patch('melissa.brain.getattr') \
                as m_getattr, \
                mock.patch('melissa.brain.actions_db') \
                as m_adb:
            # pre run
            m_adb.cur.fetchall.side_effect = fetchall_side_effect
            from melissa import brain
            # run
            brain.query(m_text)
            # test
            if m_text == 'define define':
                val_pack = ('define_subject', 'define define')
            elif m_text == 'feeling':
                val_pack = ('undefined', '')
            else:
                val_pack = ('feeling_angry', 'feeling angry')
            err_msg = (
                "Unexpected mock\'s calls. "
                "actual mock\s call:\n{}".format(
                    '\n'.join(map(repr, m_getattr.mock_calls))))
            assert len(m_getattr.mock_calls) == 2, err_msg
            assert m_getattr.mock_calls[1][1][0] == val_pack[1], err_msg
            assert m_getattr.mock_calls[0][1][1] == val_pack[0], err_msg
Exemplo n.º 9
0
    def test_simple_text_input(self):
        """test run til finished with multiple mock."""
        mock_text = 'hello world'
        with mock.patch(
                'melissa.profile_populator.profile_populator') as mock_pp:
            with mock.patch(
                    'melissa.actions_db.assemble_actions_db') \
                    as mock_acdb:
                with mock.patch('melissa.brain.actions_db') as mock_adb:
                    from melissa.brain import query
                    res = query(mock_text)
                    assert res is None
                    assert not mock_pp.called
                    assert not mock_acdb.called
                    assert not mock_adb.called

                    assert len(mock_adb.mock_calls) == 12
                    # cur.execute
                    cur_exec_calls = [
                        mock.call('DELETE FROM expression'),
                        mock.call('SELECT e.word, e.word_order,   '
                                  'g.word_group, g.word_count, g.function '
                                  'FROM expression e '
                                  'JOIN words w ON w.word = e.word '
                                  'JOIN word_groups g '
                                  'ON g.word_group = w.word_group '
                                  'WHERE g.word_count > 1 '
                                  'ORDER BY e.word_order, g.word_group'),
                        mock.call('SELECT g.function, count(*) '
                                  'as words_matched,     f.priority '
                                  'FROM expression e '
                                  'JOIN words w ON w.word = e.word '
                                  'JOIN word_groups g '
                                  'ON g.word_group = w.word_group '
                                  'JOIN functions f '
                                  'ON g.function = f.function '
                                  'WHERE g.word_count = 1 '
                                  'GROUP BY g.function ORDER BY word_count '
                                  'DESC, f.priority, g.function')
                    ]
                    assert len(mock_adb.cur.execute.mock_calls) == 3
                    for ce_call in cur_exec_calls:
                        ce_call in mock_adb.cur.execute.mock_calls
                    # cur.executemany
                    assert mock_adb.cur.executemany.call_count == 1
                    mock_adb.cur.executemany.assert_called_once_with(
                        'INSERT OR IGNORE INTO expression values (?,?)',
                        [('hello', 0), ('world', 1)]),
                    # con.commit
                    mock_adb.con.commit.assert_called_once_with()
                    # cur.fetchall
                    assert len(mock_adb.cur.fetchall.mock_calls) == 5
                    mock_adb.cur.fetchall.assert_called_with()
Exemplo n.º 10
0
def test_run_least_mock_and_working_test(m_text, fetchall_side_effect):
    """test run til finished with least mock until test work.

    this similar to test_run_least_mock function but
    add additional mock to make test working on full test.
    """
    # mocked value used on profile
    m_tts = 'xxxx'
    m_va_gender = 'female'
    # mocked value used on module
    with mock.patch('melissa.profile_loader.load_profile'):
        from melissa import profile
        profile.data = {
            'actions_db_file': ':memory:',
            'modules': 'melissa.actions',
            'tts': m_tts,
            'va_gender': m_va_gender,
        }
        with mock.patch('melissa.brain.getattr') \
                as m_getattr, \
                mock.patch('melissa.brain.actions_db') \
                as m_adb:
            # pre run
            m_adb.cur.fetchall.side_effect = fetchall_side_effect
            from melissa import brain
            # run
            brain.query(m_text)
            # test
            if m_text == 'define define':
                val_pack = ('define_subject', 'define define')
            elif m_text == 'feeling':
                val_pack = ('undefined', '')
            else:
                val_pack = ('feeling_angry', 'feeling angry')
            err_msg = ("Unexpected mock\'s calls. "
                       "actual mock\s call:\n{}".format('\n'.join(
                           map(repr, m_getattr.mock_calls))))
            assert len(m_getattr.mock_calls) == 2, err_msg
            assert m_getattr.mock_calls[1][1][0] == val_pack[1], err_msg
            assert m_getattr.mock_calls[0][1][1] == val_pack[0], err_msg
Exemplo n.º 11
0
def test_run(m_text, fetchall_retval):
    """test run til finished with multiple mock."""
    # mocked value used on profile
    m_tts = 'xxxx'
    m_va_gender = 'female'
    # mocked value used on module
    m_gen_con = mock.Mock()
    with mock.patch('melissa.profile_loader.load_profile'):
        from melissa import profile
        profile.data = {
            'actions_db_file': ':memory:',
            'modules': 'melissa.actions',
            'tts': m_tts,
            'va_gender': m_va_gender,
        }
        with mock.patch('melissa.brain.actions_db') \
                as m_adb, \
                mock.patch('melissa.brain.getattr') \
                as m_getattr:
            # pre run
            from melissa import brain
            m_adb.modules = {'general_conversations': m_gen_con}
            m_adb.cur.fetchall.return_value = fetchall_retval
            if isinstance(m_text, mock.Mock):
                with pytest.raises(TypeError):
                    brain.query(m_text)
                assert not m_adb.mock_calls
            elif fetchall_retval == [M_RETVAL]:
                with pytest.raises(TypeError):
                    brain.query(m_text)
            elif m_text == '' or m_text == 'define programming':
                # run
                brain.query(m_text)
                # test
                getattr_calls = [
                    mock.call(m_gen_con, 'undefined'),
                    mock.call()('')
                ]
                m_getattr.assert_has_calls(getattr_calls)
                if m_text == '':
                    executemany_arg = []
                elif m_text == 'define programming':
                    executemany_arg = [('define', 0), ('programming', 1)]
                adb_calls = [
                    mock.call.cur.execute('DELETE FROM expression'),
                    mock.call.cur.executemany(
                        'INSERT OR IGNORE INTO expression values (?,?)',
                        executemany_arg),
                    mock.call.con.commit(),
                    mock.call.cur.execute(
                        'SELECT e.word, e.word_order,   '
                        'g.word_group, g.word_count, g.function '
                        'FROM expression e '
                        'JOIN words w ON w.word = e.word '
                        'JOIN word_groups g ON g.word_group = w.word_group '
                        'WHERE g.word_count > 1 '
                        'ORDER BY e.word_order, g.word_group'),
                    mock.call.cur.fetchall(),
                    mock.call.cur.execute(
                        'SELECT g.function, count(*) as words_matched,     '
                        'f.priority FROM expression e '
                        'JOIN words w ON w.word = e.word '
                        'JOIN word_groups g ON g.word_group = w.word_group '
                        'JOIN functions f ON g.function = f.function '
                        'WHERE g.word_count = 1 GROUP BY g.function '
                        'ORDER BY word_count DESC, f.priority, g.function'),
                    mock.call.cur.fetchall(),
                ]
                m_adb.assert_has_calls(adb_calls)
Exemplo n.º 12
0
    def on_chat_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance(msg)
        if (content_type == 'text') and (str(chat_id) in allowed_chat_ids):
            command = msg['text'].lower()
            print(command)

            ### GENERIC METHODS ###
            if command == '/roll':
                bot.sendMessage(chat_id, 'dice')
            elif command == '/start':
                bot.sendMessage(chat_id, 'hola!')
            elif command == '/menu':
                replymarkup = {
                    "keyboard": [[{
                        "text": "/alarm"
                    }], [{
                        "text": "/favstates"
                    }], [{
                        "text": "/roll"
                    }]],
                    "resize_keyboard":
                    True,
                    "one_time_keyboard":
                    True
                }
                bot.sendMessage(chat_id,
                                'Please choose an option...',
                                reply_markup=replymarkup)

            ### ACTION COMMANDS ###
            elif command == '/actions':
                replymarkup = {
                    "keyboard": [[{
                        "text": "/sleep"
                    }], [{
                        "text": "/home"
                    }], [{
                        "text": "/grocery_list"
                    }]],
                    "resize_keyboard":
                    True,
                    "one_time_keyboard":
                    False
                }
                bot.sendMessage(chat_id,
                                'Please choose an option...',
                                reply_markup=replymarkup)
            elif command == '/sleep':
                bot.sendMessage(chat_id, 'Goodnight')
            else:
                query(command, bot, chat_id)

        ### ELSE NOT TEXT ###
        elif (content_type == 'location') and (str(chat_id)
                                               in allowed_chat_ids):
            latitude = msg['location']['latitude']
            longitude = msg['location']['longitude']
            bot.sendMessage(chat_id, 'You are checked in.')
        elif (content_type == 'audio') and (str(chat_id) in allowed_chat_ids):
            mimetype = msg['audio']['mime_type']
            print(mimetype)
            bot.sendMessage(chat_id, mimetype)
        else:
            bot.sendMessage(chat_id, 'You are not allowed to chat with me.')
Exemplo n.º 13
0
def test_run(m_text, fetchall_retval):
    """test run til finished with multiple mock."""
    # mocked value used on profile
    m_tts = 'xxxx'
    m_va_gender = 'female'
    # mocked value used on module
    m_gen_con = mock.Mock()
    with mock.patch('melissa.profile_loader.load_profile'):
        from melissa import profile
        profile.data = {
            'actions_db_file': ':memory:',
            'modules': 'melissa.actions',
            'tts': m_tts,
            'va_gender': m_va_gender,
        }
        with mock.patch('melissa.brain.actions_db') \
                as m_adb, \
                mock.patch('melissa.brain.getattr') \
                as m_getattr:
            # pre run
            from melissa import brain
            m_adb.modules = {
                'general_conversations': m_gen_con}
            m_adb.cur.fetchall.return_value = fetchall_retval
            if isinstance(m_text, mock.Mock):
                with pytest.raises(TypeError):
                    brain.query(m_text)
                assert not m_adb.mock_calls
            elif fetchall_retval == [M_RETVAL]:
                with pytest.raises(TypeError):
                    brain.query(m_text)
            elif m_text == '' or m_text == 'define programming':
                # run
                brain.query(m_text)
                # test
                getattr_calls = [
                    mock.call(m_gen_con, 'undefined'),
                    mock.call()('')
                ]
                m_getattr.assert_has_calls(getattr_calls)
                if m_text == '':
                    executemany_arg = []
                elif m_text == 'define programming':
                    executemany_arg = [('define', 0), ('programming', 1)]
                adb_calls = [
                    mock.call.cur.execute('DELETE FROM expression'),
                    mock.call.cur.executemany(
                        'INSERT OR IGNORE INTO expression values (?,?)',
                        executemany_arg),
                    mock.call.con.commit(),
                    mock.call.cur.execute(
                        'SELECT e.word, e.word_order,   '
                        'g.word_group, g.word_count, g.function '
                        'FROM expression e '
                        'JOIN words w ON w.word = e.word '
                        'JOIN word_groups g ON g.word_group = w.word_group '
                        'WHERE g.word_count > 1 '
                        'ORDER BY e.word_order, g.word_group'),
                    mock.call.cur.fetchall(),
                    mock.call.cur.execute(
                        'SELECT g.function, count(*) as words_matched,     '
                        'f.priority FROM expression e '
                        'JOIN words w ON w.word = e.word '
                        'JOIN word_groups g ON g.word_group = w.word_group '
                        'JOIN functions f ON g.function = f.function '
                        'WHERE g.word_count = 1 GROUP BY g.function '
                        'ORDER BY word_count DESC, f.priority, g.function'),
                    mock.call.cur.fetchall(),
                ]
                m_adb.assert_has_calls(adb_calls)