# Path: zdict/completer.py
# class DictCompleter:
#     def __init__(self):
#         self.db = db
#         self.db.connection()
# 
#     def __del__(self):
#         self.db.close()
# 
#     def complete(self, text, state):
#         if state == 0:  # new query
#             self.records = iter(
#                 Record.select().where(Record.word.startswith(text)))
# 
#         return next(self.records).word


from pytest import raises
from unittest.mock import patch, Mock
from zdict.completer import DictCompleter


@patch('zdict.completer.db')
def test_DictCompleter_db_connect(db):
    '''
    Test case for DictCompleter init/del

    DictCompleter will connect to db when __init__,
    and close db when __del__.
    '''
    # init
    completer = DictCompleter()
    assert db.connection.called

    # del
    del completer
    assert db.close.called


@patch('zdict.completer.Record')
@patch('zdict.completer.db')
def test_DictCompleter_complete(db, Record):
    '''
    Test case for DictCompleter.complete implemented with iterator
    '''
    # Assume our db contains following words
    Record.select().where.return_value = [
        Mock(word='apple'),
        Mock(word='apply')]


# Path: zdict/completer.py
# class DictCompleter:
#     def __init__(self):
#         self.db = db
#         self.db.connection()
# 
#     def __del__(self):
#         self.db.close()
# 
#     def complete(self, text, state):
#         if state == 0:  # new query
#             self.records = iter(
#                 Record.select().where(Record.word.startswith(text)))
# 
#         return next(self.records).word


# Path: zdict/tests/test_completer.py
from pytest import raises
from unittest.mock import patch, Mock
from zdict.completer import DictCompleter



@patch('zdict.completer.db')
def test_DictCompleter_db_connect(db):
    '''
    Test case for DictCompleter init/del

    DictCompleter will connect to db when __init__,
    and close db when __del__.
    '''
    # init
    completer = DictCompleter()
    assert db.connection.called

    # del
    del completer
    assert db.close.called


@patch('zdict.completer.Record')
@patch('zdict.completer.db')
def test_DictCompleter_complete(db, Record):
    '''
    Test case for DictCompleter.complete implemented with iterator
    '''
    # Assume our db contains following words
    Record.select().where.return_value = [
        Mock(word='apple'),
        Mock(word='apply')]


    completer = DictCompleter()