예제 #1
0
    async def test_establish_session_async(self, mocker: MockerFixture,
                                           target: ClientChannel) -> None:
        # Arrange
        compression = SessionCompression.GZIP
        encryption = SessionEncryption.TLS
        identity = TO
        authentication = PlainAuthentication('any-pswd')
        instance = 'test'

        target.state = SessionState.NEW

        start_result = Session(SessionState.AUTHENTICATING)

        auth_result = Session(SessionState.ESTABLISHED)

        mocker.patch.object(  # noqa: WPS316
            target,
            'start_new_session_async',
            return_value=self.__async_return(start_result))
        mocker.patch.object(target,
                            'authenticate_session_async',
                            return_value=self.__async_return(auth_result))

        # Act
        result: Future = await target.establish_session_async(
            compression, encryption, identity, authentication, instance)

        # Assert
        assert result == Session(SessionState.ESTABLISHED)
예제 #2
0
def get_dataFrame(table):
    """
    combine all data in database into dataframe format
    'basically this function f**k up everything!'
    But we still get the data out from the db,right?
    :param table:
    :return:
    """
    s = Session()
    result = s.query(table.store_name,table.city,table.store_number,table.brand,\
                     table.ownership_type,table.street_address,table.country,table.postcode,table.phone_number,\
                     table.longitude,table.latitude,table.timezone,table.stateprovince).all()
    result_list = src.controller.no_frameobj_helper.row_into_list(
        src.controller.no_frameobj_helper.get_seperate_list(result))
    starbucks = {}
    starbucks["Store Name"] = result_list[0]
    starbucks["City"] = result_list[1]
    starbucks["Store Number"] = result_list[2]
    starbucks["Brand"] = result_list[3]
    starbucks["Ownership Type"] = result_list[4]
    starbucks["Street Address"] = result_list[5]
    starbucks["Country"] = result_list[6]
    starbucks["Postcode"] = result_list[7]
    starbucks["Phone Number"] = result_list[8]
    starbucks["Longitude"] = result_list[9]
    starbucks["Latitude"] = result_list[10]
    starbucks["Timezone"] = result_list[11]
    starbucks["State/Province"] = result_list[12]

    dataframe = DataFrame(starbucks)

    s.close()
    return dataframe
예제 #3
0
    def test_on_envelope_session(self, mocker: MockerFixture) -> None:
        # Arrange
        channel = self.__get_target()
        session = Session(SessionState.FINISHED)
        spy = mocker.spy(channel, 'on_session')

        # Act
        channel.on_envelope(session.to_json())

        # Assert
        spy.assert_called_once_with(session)
예제 #4
0
    async def test_on_session_failed(self, mocker: MockerFixture,
                                     target: ClientChannel) -> None:
        # Arrange
        session = Session(SessionState.FAILED)
        session.id = SESSION_ID

        spy_transport = mocker.spy(target.transport, 'close_async')
        # Act
        target.on_session(session)

        # Assert
        spy_transport.assert_called_once()
예제 #5
0
    async def test_on_session_authenticating(self, mocker: MockerFixture,
                                             target: ClientChannel) -> None:
        # Arrange
        session = Session(SessionState.AUTHENTICATING)
        session.id = SESSION_ID

        spy = mocker.spy(target, 'on_session_authenticating')
        # Act
        target.on_session(session)

        # Assert
        spy.assert_called_once_with(session)
예제 #6
0
    async def test_start_new_session_async(self, mocker: MockerFixture,
                                           target: ClientChannel) -> None:
        # Arrange
        target.state = SessionState.NEW

        spy = mocker.spy(target, SEND_SESSION_METHOD)
        sent_session = Session(SessionState.NEW)

        # Act
        target.start_new_session_async()

        # Assert
        sent_session.id = spy.call_args[0][0].id
        spy.assert_called_once_with(sent_session)
예제 #7
0
    async def test_send_finishing_session_async(self, mocker: MockerFixture,
                                                target: ClientChannel) -> None:
        # Arrange
        target.state = SessionState.ESTABLISHED
        target.session_id = SESSION_ID

        spy = mocker.spy(target, SEND_SESSION_METHOD)
        sent_session = Session(SessionState.FINISHING)
        sent_session.id = SESSION_ID

        # Act
        target.send_finishing_session_async()

        # Assert
        spy.assert_called_once_with(sent_session)
예제 #8
0
    async def test_on_session_established(self, mocker: MockerFixture,
                                          target: ClientChannel) -> None:
        # Arrange
        session = Session(SessionState.ESTABLISHED)
        session.id = SESSION_ID
        session.to = TO
        session.from_n = FROM_N

        spy = mocker.spy(target, 'on_session_established')
        # Act
        target.on_session(session)

        # Assert
        spy.assert_called_once_with(session)
        assert target.local_node == str(session.to)
        assert target.remote_node == session.from_n
예제 #9
0
def get_number_of_country(table, times):
    '''
    获得全球范围内前n的国家
    :param table:
    :param times:
    :return:
    '''
    s = Session()
    #the store count of country
    count = func.count(table.country)
    #select top n of country and their store numbers
    result = s.query(table.country, count).group_by(table.country).order_by(
        count.desc()).limit(times)
    result_list = src.controller.no_frameobj_helper.row_into_list(result)
    s.close()
    return result_list
예제 #10
0
    def test_ensure_not_allowed_states(self) -> None:
        # Arrange
        channel = self.__get_target(SessionState.FAILED)
        session = Session(SessionState.AUTHENTICATING)

        # Assert
        with pytest.raises(ValueError):
            channel.send_command(session)
예제 #11
0
    async def test_negotiate_session_async(self, mocker: MockerFixture,
                                           target: ClientChannel) -> None:
        # Arrange
        target.state = SessionState.NEGOTIATING

        spy = mocker.spy(target, SEND_SESSION_METHOD)
        sent_session = Session(SessionState.NEGOTIATING,
                               compression=SessionCompression.GZIP,
                               encryption=SessionEncryption.TLS)

        # Act
        target.negotiate_session_async(SessionCompression.GZIP,
                                       SessionEncryption.TLS)

        # Assert
        sent_session.id = spy.call_args[0][0].id
        spy.assert_called_once_with(sent_session)
예제 #12
0
def get_position(table, range='world', country_code=None):

    s = Session()

    if range == 'world':
        #返回世界范围的店铺位置信息
        result = s.query(distinct(table.store_name), table.city,
                         table.longitude, table.latitude).all()
        result_list = src.controller.no_frameobj_helper.row_into_list(result)
        return result_list
    elif range == 'country' and src.controller.no_frameobj_helper.check_if_valid(
            country_code):
        #返回某个国家的店铺位置信息
        city_count = func.count(table.city)
        store_city_count = s.query(
            table.city,
            city_count).filter(table.country == country_code).group_by(
                table.city).order_by(city_count.desc()).all()
        store_position = s.query(table.store_name,table.city,table.longitude,table.latitude).filter(table.country==country_code)\
        .group_by(table.store_name).all()

        count = src.controller.no_frameobj_helper.row_into_list(
            store_city_count)
        position = src.controller.no_frameobj_helper.row_into_list(
            store_position)
        return count, position

    else:
        print("Invalid parameters!")

    s.close()
예제 #13
0
    def test_is_session_should_be_true(self):
        # Arrange
        envelope = Session('new')

        # Act
        result = Envelope.is_session(envelope)

        # Assert
        assert result is True
예제 #14
0
    def test_is_command_should_be_false(self):
        # Arrange
        envelope = Session('new')

        # Act
        result = Envelope.is_command(envelope)

        # Assert
        assert result is False
예제 #15
0
    def test_is_notification_should_be_false(self):
        # Arrange
        envelope = Session('new')

        # Act
        result = Envelope.is_notification(envelope)

        # Assert
        assert result is False
예제 #16
0
def select_city_from_country(table, times, country_code):
    '''
    获得指定国家前n的城市信息
    :param table:
    :param times:
    :param country_code:
    :return:
    '''

    if src.controller.no_frameobj_helper.check_if_valid(country_code):
        s = Session()
        count = func.count(table.city)
        result = s.query(table.city,
                         count).filter(table.country == country_code).group_by(
                             table.city).order_by(count.desc()).limit(times)
        result_list = src.controller.no_frameobj_helper.row_into_list(result)
        s.close()
        return result_list
    else:
        print("Invalid country code!")
예제 #17
0
def get_ownership_percentage(table):
    '''
    获得全球范围内的所有种类占比
    :param table:
    :return:
    '''
    s = Session()
    count = func.count(table.ownership_type)
    result = s.query(table.ownership_type, count).group_by(
        table.ownership_type).order_by(count.desc()).all()

    # total_record = count_distinct_records_total(table.ownership_type,False)
    result_list = []
    for k, v in result:
        percent = v
        # percent = '%.2f%%' % (v / total_record * 100)
        result_dict = (k, percent)
        result_list.append(result_dict)
    s.close()
    return result_list
예제 #18
0
def cliQuery():
    dbCopyScript = path.join(path.abspath(path.dirname(__file__)), 'dbCopy.sh')
    subprocess.call(dbCopyScript, shell=True)
    user = environ['USER']
    tmpEngine = create_engine('sqlite:////tmp/' + user +
                              '/module-query/tempDB/app.db')
    Session.configure(bind=tmpEngine)
    session = Session()
    try:
        yield session
    finally:
        session.close()
        Session.configure(bind=engine)
예제 #19
0
    async def test_authenticate_session_async(self, mocker: MockerFixture,
                                              target: ClientChannel) -> None:
        # Arrange
        target.state = SessionState.AUTHENTICATING
        target.session_id = SESSION_ID

        spy = mocker.spy(target, SEND_SESSION_METHOD)
        identity = '*****@*****.**'
        instance = 'test'
        authentication = PlainAuthentication('any-pswd')
        sent_session = Session(SessionState.AUTHENTICATING,
                               scheme=authentication.scheme,
                               authentication=authentication)
        sent_session.from_n = f'{identity}/{instance}'
        sent_session.id = SESSION_ID

        # Act
        target.authenticate_session_async(identity, authentication, instance)

        # Assert
        spy.assert_called_once_with(sent_session)
예제 #20
0
def get_country_store_info(table, country_code):
    '''
    获得指定城市的基本信息
    :param table:
    :param country_code:
    :return:
    '''

    if src.controller.no_frameobj_helper.check_if_valid(country_code):
        s = Session()
        basic = s.query(
            table.city, table.store_number, table.store_name,
            table.street_address).filter(table.country == country_code).all()
        count = s.query(func.count(
            table.store_name)).filter(table.country == country_code).all()
        for row in count:
            count = row[0]

        basic_info = src.controller.no_frameobj_helper.row_into_list(basic)
        top_ten = select_city_from_country(table, 10, country_code)

        s.close()
        result_list = [count, basic_info, top_ten]

        return result_list
    else:
        print("Invalid country code!(ex: 'AE')")
예제 #21
0
def count_distinct_records_total(table_row, count_distinct=True):
    '''
    获得不重复的列结果集
    :param table_row:
    :param count_distinct:
    :return:
    '''

    s = Session()
    if count_distinct:
        result = s.query(func.count(distinct(table_row)))
    else:
        result = s.query(func.count(table_row))
    count = 0
    for row in result:
        count = row[0]

    s.close()
    return count
import sys

from src import Config, Session

if __name__ == '__main__':
    if len(sys.argv) != 5:
        raise Exception(
            "Usage: python run.py <API Key> <Engine Key> <Precision> <Query in double quotation marks>"
        )

    config = Config(dev_key=sys.argv[1],
                    engine_key=sys.argv[2],
                    precision=float(sys.argv[3]),
                    query=sys.argv[4].split(" "))

    Session(config).run()
예제 #23
0
def dbMaintenance():
    session = Session()
    try:
        yield session
    finally:
        session.close()