Best Python code snippet using tempest_python
credit_card.py
Source:credit_card.py  
...29        if shop_cassify_id == "0":30            exitflag = True31            continue32        if int(shop_cassify_id) not in range(1, 6):33            common.show_message("è¯·éæ©æ£ç¡®çååç±»åç¼å·!", "ERROR")34            continue35        elif shop_cassify_id == "4":36            # æ¥çè´ç©è½¦37            shopping.Shopping.print_goods_list(shoppobj.shopping_cart)38            common.show_message("å½åè´ç©è½¦å
±æ {0} ä»¶åå,å计 {1} å
 !".format(len(shoppobj.shopping_cart),39                                                                    shoppobj.shopping_cost), "INFORMATION")40            continue41        elif shop_cassify_id == "5":42            # è´ç©ç»ç®43            dealresult = shoppobj.payfor_shopcart(userobj)44            if dealresult == errorcode.NO_ERROR:45                common.show_message("æ¯ä»å®æ!", "INFORMATION")46        else:47            # è·åç¨æ·éæ©çååç±»åç¼å·48            shoppobj.goods_classify_id = shop_cassify_id49            # è·å¾ååç±»åç¼å·å¯¹åºçååå表50            goods_list = shoppobj.get_goods_list_by_typeid()51            if not goods_list:52                common.show_message("æªæ¾å°ååä¿¡æ¯ï¼", "NOTICE")53                continue54            # å¼å§éæ©ååï¼æ·»å å°è´ç©è½¦55            choose_goods_flag = True56            while choose_goods_flag:57                # æ¾ç¤ºæå®åååç±»ä¸çææååå表(Shoppingç±»éææ¹æ³)58                shopping.Shopping.print_goods_list(goods_list)59                goods_id = raw_input("éæ©ååç¼å·,å å
¥è´ç©è½¦(qè¿åä¸ä¸çº§): ").strip().lower()60                if not goods_id: continue61                # è¿åä¸ä¸çº§62                if goods_id == "q":63                    choose_goods_flag = False64                    continue65                else:66                    # å°éæ©ååå å
¥è´ç©è½¦67                    result = shoppobj.add_shopping_card(goods_id)68                    if result:69                        # æ·»å æå,æ¾ç¤ºè´ç©è½¦ææååä¿¡æ¯70                        shopping.Shopping.print_goods_list(shoppobj.shopping_cart)71                        common.show_message("å·²å°ååå å
¥è´ç©è½¦!", "INFORMATION")72                        # æ¯å¦ç»§ç»æ·»å 73                        nextflag = False74                        while not nextflag:75                            donext = raw_input("ç»§ç»è´ç©(y) or è¿åä¸ä¸çº§(q):").strip().lower()76                            if donext == "y":77                                break78                            elif donext == "q":79                                choose_goods_flag = False80                                break81                            else:82                                continue83                    else:84                        # æ·»å è´ç©è½¦å¤±è´¥85                        common.show_message("æ·»å è´ç©è½¦å¤±è´¥,è¯·æ£æ¥è¾å
¥ååç¼å·æ¯å¦æ£ç¡®!", "ERROR")86                        continue87def user_login(userobj, today, weekoftoday):88    """89    主èåç2å·èåç»å½ç³»ç»æ¨¡å90    :param userobj: å½åç¨æ·å¯¹è±¡91    :param today: èåæ¾ç¤ºçæ¥æ92    :param weekoftoday: èåæ¾ç¤ºçææ93    :return:94    """95    quitflag = False96    while not quitflag:97        if userobj.islogin:98            # å¦æç¨æ·å·²ç»ç»å½,èååè½2为个人ä¸å¿,è°ç¨å¦ä¸ä¸ªè忍¡æ¿ index_user_center99            print(templates.index_user_center.format(userobj.name, today, common.numtochr(weekoftoday)))100            _chooseflag = False101            while not _chooseflag:102                _choose = raw_input("éæ©åè½ï¼")103                if _choose not in ("1", "2", "3", "4", "5", "6"):104                    common.show_message("éæ©æ£ç¡®çåè½ç¼å·!", "ERROR")105                    continue106                else:107                    _chooseflag = True108            # è¿åä¸çº§èå109            if _choose == "6":110                quitflag = True111            else:112                # æ ¹æ®ç¨æ·æé®å¼å§å¤ç,ä» template æ¨¡åæ¥æ¾åæé®å¯¹åºç模å,éè¿åå°æ¥æ§è¡113                func_dict = templates.user_center_func114                modulepy = __import__(func_dict[_choose]["module"])115                # 1,2,5å·é®ä¸ºusersç±»æ¹æ³ï¼116                if _choose in ('1', '2', '5'):117                    modulesobj = getattr(modulepy, "users")118                    classobj = getattr(modulesobj, "Users")119                    func = getattr(classobj, func_dict[_choose]["func"])120                else:121                    # 3,4为 report 模åçæ¹æ³122                    modulesobj = getattr(modulepy, "report")123                    func = getattr(modulesobj, func_dict[_choose]["func"])124                func(userobj)125        else:126            # ç¨æ·æªç»å½,è°ç¨ Usersç±»çç»å½æ¨¡å127            userobj.login()128            quitflag = True129def card_center(userobj):130    if userobj.islogin:131        # éæ°loadä¸ä¸æ°æ®132        userobj.db_load()133        cardno = userobj.bindcard134        # è·å¾ä¿¡ç¨å¡å¯¹è±¡135        card = CreditCard(cardno)136    else:137        # æªç»å½ä¿¡ç¨å¡138        input_flag = False139        while not input_flag:140            cardno = unicode(raw_input("请è¾å
¥ä¿¡ç¨å¡å¡å·: ").strip().lower())141            if cardno.isnumeric():142                card = CreditCard(cardno)143                if card.card_is_exists:144                    pwd = raw_input("请è¾å
¥å¯ç :")145                    if common.encrypt(pwd) == card.password:146                        common.show_message("ç»å½æå", "NOTICE")147                        input_flag = True148                        continue149                else:150                    common.show_message("å¡å·ä¸åå¨,è¯·éæ°è¾å
¥!", "ERROR")151                    continue152            else:153                common.show_message("å¡å·æ æ!", "ERROR")154                continue155    show_template = templates.index_ATM156    quitflag = False157    while not quitflag:158        print(show_template.format(cardno=card.cardno))159        _choose = common.input_msg("è¯·éæ©åè½: ", ("1", "2", "3", "4", "5"))160        # è¿å161        if _choose == "5":162            quitflag = True163            continue164        # æ¥çä¿¡ç¨å¡ä¿¡æ¯165        if _choose == "1":166            common.show_message(templates.card_info.format(cardno=card.cardno,167                                                          owner=card.owner,168                                                          total=card.credit_total,169                                                          balance=card.credit_balance,170                                                          status="æ£å¸¸" if card.frozenstatus == 0 else "å»ç»"171                                                          ), "NOTICE")172        # æç°173        if _choose == "2":174            if card.frozenstatus == 1:175                common.show_message("å¡å·²å»ç»,请è系客æ!", "ERROR")176            else:177                common.show_message("ä¿¡ç¨å¡æç°å°æ¶å {0}% çæç»è´¹!".format(settings.FETCH_MONEY_RATE * 100), "NOTICE")178                quitflag = False179                while not quitflag:180                    cost = common.input_msg("请è¾å
¥è¦æç°çéé¢(qè¿å):")181                    cost = unicode(cost)182                    if cost.isnumeric():  # Python isnumeric() æ¹æ³æ£æµå符串æ¯å¦åªç±æ°åç»æãè¿ç§æ¹æ³æ¯åªé对unicode对象183                        cardpasswd = common.input_msg("请è¾å
¥ä¿¡ç¨å¡å¯ç :")184                        # æ§è¡æç°æä½185                        exe_result = card.fetch_money(float(cost), cardpasswd)186                        if exe_result == errorcode.NO_ERROR:187                            common.show_message("已宿æç°ï¼", "NOTICE")188                        if exe_result == errorcode.BALANCE_NOT_ENOUGHT:189                            common.show_message("ä¿¡ç¨å¡å¯éæ¯ä½é¢ä¸è¶³!", "ERROR")190                        if exe_result == errorcode.CARD_PASS_ERROR:191                            common.show_message("ä¿¡ç¨å¡å¯ç é误!", "ERROR")192                    elif cost == "q":193                        quitflag = True194                        continue195                    else:196                        common.show_message("è¾å
¥é误!", "ERROR")197        # 转账198        if _choose == "3":199            if card.frozenstatus == 1:200                common.show_message("æ¤å¡å·²å»ç»,请è系客æ!", "ERROR")201            else:202                common.show_message("ä¿¡ç¨å¡è½¬è´¦å°æ¶å {0}% çæç»è´¹!".format(settings.FETCH_MONEY_RATE * 100), "NOTICE")203                quitflag = False204                while not quitflag:205                    trans_cardno = unicode(common.input_msg("请è¾å
¥è¦è½¬è´¦çå¡å·(qè¿å):"))206                    if trans_cardno.isnumeric():207                        # çæä¸ä¸ªå¡å¯¹è±¡, éªè¯å¡å·æ¯å¦åå¨208                        trans_cardobj = CreditCard(trans_cardno)209                        # å¡å·ä¸åå¨è¿å主èå210                        if not trans_cardobj.card_is_exists:211                            common.show_message("å¡å·ä¸åå¨,请确认!", "ERROR")212                            quitflag = True213                            continue214                        else:215                            # å¡å·åå¨216                            trans_cost = unicode(common.input_msg("请è¾å
¥è¦è½¬è´¦çéé¢: "))217                            # 妿è¾å
¥çå为æ°å218                            if trans_cost.isnumeric():219                                comfirm = common.input_msg("ç¡®å®è¦ç»å¡å· {0} 转å
¥äººæ°å¸ {1} å
å(y/n)?".format(trans_cardobj.cardno,220                                                                                                  trans_cost),221                                                           ("y", "n"))222                                if comfirm == "y":223                                    cardpasswd = common.input_msg("请è¾å
¥ä¿¡ç¨å¡å¯ç :")224                                    # æ§è¡è½¬è´¦æä½225                                    exe_result = card.translate_money(float(trans_cost), cardpasswd, trans_cardobj)226                                    if exe_result == errorcode.NO_ERROR:227                                        common.show_message("è½¬è´¦å®æï¼", "NOTICE")228                                    if exe_result == errorcode.BALANCE_NOT_ENOUGHT:229                                        common.show_message("ä¿¡ç¨å¡å¯éæ¯ä½é¢ä¸è¶³!", "ERROR")230                                    if exe_result == errorcode.CARD_PASS_ERROR:231                                        common.show_message("ä¿¡ç¨å¡å¯ç é误!", "ERROR")232                            else:233                                common.show_message("è¾å
¥é误!", "ERROR")234                    elif trans_cardno == "q":235                        quitflag = True236                        continue237                    else:238                        common.show_message("è¾å
¥é误!", "ERROR")239        # è¿æ¬¾240        if _choose == "4":241            # æ´æ°ä¸ä¸å¯¹è´¦åä¿¡æ¯242            card.recreate_statement()243            quitflag = False244            while not quitflag:245                # è·åå¯¹è´¦åææå表246                interest_list = card.load_statement_list()247                # è·åè¿æªè¿æ¬¾çè®°å½å¹¶æ¾ç¤º248                message_info = report.print_statement_list(card.cardno, interest_list)249                # 妿æè¦è¿æ¬¾çè®°å½250                if len(message_info) > 0:251                    common.show_message(message_info, "NOTICE")252                    # è¾å
¥è¦è¿æ¬¾çåå·253                    serino_list = list()254                    for order in interest_list:255                        serino_list.append(list(order.keys())[0])256                    serino_list.append("q")257                    pay_serno = common.input_msg("è¯·éæ©è¿æ¬¾ç16ä½è´¦åå·(qéåº)ï¼", tuple(serino_list))258                    if pay_serno == "q":259                        quitflag = True260                        continue261                    else:262                        for i in range(len(interest_list)):263                            for k, details in interest_list[i].items():264                                if k == pay_serno:265                                    # æ¾ç¤ºæå®åå·çç¸ä¿¡å¯¹è´¦åä¿¡æ¯266                                    common.show_message(report.print_statement_detail(card.cardno,267                                                                                      pay_serno,268                                                                                      details),269                                                        "NOTICE")270                                    pay_fee = common.input_msg("请è¾å
¥è¿æ¬¾éé¢:")271                                    if pay_fee.isnumeric():272                                        # æ´æ°å·²è¿æ¬¾éé¢ = ç°å¨è¿çéé¢ + å·²ç»è¿çéé¢273                                        total_payed = details["payed"] + float(pay_fee)274                                        interest_list[i][pay_serno]["payed"] = total_payed275                                        # å
¨è¿äºåï¼éè¦è¿æ¬¾æ° = æ¶è´¹æ»è´¹ç¨ + 婿¯276                                        need_pay = details["total"] + details["interest"]277                                        if total_payed >= need_pay:278                                            # è¿æ¬¾æ°å¤§äºçäºéè¦è¿æ¬¾æ°ï¼åæ´æ°å·²è¿æ¬¾å段信æ¯279                                            interest_list[i][pay_serno]["isfinished"] = 1280                                        else:281                                            # 没å
¨é¨è¿æ¬¾282                                            common.show_message("æ¨å°æªå
¨é¨è¿æ¬¾,请å¨è¿æ¬¾æ¥åå°½å¿«è¿æ¬¾!", "NOTICE")283                                        # å°è¿æ¬¾åçä¿¡æ¯åå
¥æ°æ®åºæ´æ°284                                        dbapi.write_statement_list(card.cardno, interest_list)285                                        # è¿æ¬¾æå286                                        common.show_message("è¿æ¬¾æå", "NOTICE")287                                        # æ¯å¦ç»§ç»288                                        iscontinue = common.input_msg("ç»§ç»è¿æ¬¾å(y/n)?", ("y", "n"))289                                        if iscontinue == "n":290                                            quitflag = True291                                    else:292                                        common.show_message("è¾å
¥æ°æ®ä¸æ£ç¡®ï¼è¯·éæ°è¾å
¥!", "ERROR")293                else:294                    common.show_message("æ è´¦åä¿¡æ¯ï¼", "NOTICE")295                    quitflag = True296def get_users():297    """298    æ¾ç¤ºç¨æ·çä¿¡æ¯,ç¨æ·æ°å»ºãå é¤ãè§£éç¨æ·æ¶æ¾ç¤ºç¨æ·åºæ¬ä¿¡æ¯299    :return:300    """301    username = common.input_msg("请è¾å
¥ç¨æ·å:")302    # å建ä¸ä¸ªç¨æ·å®ä¾303    _deluser = Users()304    _deluser.username = username305    # å¦æç¨æ·ååå¨,loadç¨æ·ä¿¡æ¯æå306    if _deluser.load_user_info():307        # å
æ¾ç¤ºä¸ä¸ç¨æ·çä¿¡æ¯308        common.show_message(templates.user_info.format(username=_deluser.username,309                                                      name=_deluser.name,310                                                      mobile=_deluser.mobile,311                                                      role=_deluser.role,312                                                      isdel="å¦" if _deluser.isdel == 0 else "æ¯",313                                                      islocked="å¦" if _deluser.islocked == 0 else "æ¯",314                                                      bindcard=_deluser.bindcard)315                            , "NOTICE")316        return _deluser317    else:318        common.show_message("ç¨æ·åä¸åå¨!", "ERROR")319        return False320def fill_card_info():321    """322    å¡«å
ä¿¡ç¨å¡èµæä¿¡æ¯323    :return: è¿åä¸ä¸ªä¿¡ç¨å¡å¯¹è±¡324    """325    retry_flag = False326    while not retry_flag:327        cardno = common.input_msg("请è¾å
¥å¡å·:")328        cardobj = CreditCard(cardno)329        if cardobj.card_is_exists:330            common.show_message("å¡å·å·²åå¨,è¯·éæ°è¾å
¥å¡å·", "ERROR")331            continue332        else:333            retry_flag = True334            continue335    cardobj.password = common.input_msg("请è¾å
¥å¯ç :")336    cardobj.credit_total = common.input_msg("ä¿¡ç¨é¢åº¦(default:{0}):".format(cardobj.credit_total))337    cardobj.credit_balance = cardobj.credit_total338    cardobj.owner = common.input_msg("ææè
:")339    return cardobj340def manager(userobj):341    """342    主èååå°ç®¡ç模å343    :param userobj: å½åç»å½ç¨æ·å¯¹è±¡344    :return:345    """346    if userobj.islogin:347        if userobj.role == "admin":348            quit_flag = False349            while not quit_flag:350                _show_template = templates.index_admin351                print(_show_template.format(username=userobj.name))352                _choose = input("éæ©æä½åè½: ").strip().lower()353                # å建æ°ç¨æ·354                if _choose == "1":355                    _newuser = Users()356                    # è°ç¨åå§åç¨æ·å½æ°å建æ°ç¨æ·357                    _newuser.init_user_info()358                # å é¤ç¨æ·359                if _choose == "2":360                    _user = get_users()361                    if _user:362                        confirm = common.input_msg("ç¡®å®è¦å é¤æ¤ç¨æ·å(y/n)?", ("y", "n"))363                        if confirm == "y":364                            _user.del_user()365                            common.show_message("ç¨æ·å é¤æå!", "NOTICE")366                # è§£éç¨æ·367                if _choose == "3":368                    _user = get_users()369                    if _user:370                        confirm = common.input_msg("确认解éå(y/n)?", ("y", "n"))371                        if confirm == "y":372                            _user.unlock_user()373                            common.show_message("ç¨æ·è§£éæå!", "NOTICE")374                # åè¡ä¿¡ç¨å¡375                if _choose == "4":376                    newcard = fill_card_info()377                    newcard.create_card()378                    common.show_message("å塿å!", "NOTICE")379                # å»ç»ä¿¡ç¨å¡380                if _choose == "5":381                    cardno = common.input_msg("è¾å
¥å¡å·:")382                    card = CreditCard(cardno)383                    if not card.card_is_exists:384                        common.show_message("å¡å·ä¸åå¨", "ERROR")385                    else:386                        # è°ç¨æ¨¡æ¿æ¾ç¤ºå¡ä¿¡æ¯387                        common.show_message(templates.card_info.format(cardno=card.cardno,388                                                                      owner=card.owner,389                                                                      total=card.credit_total,390                                                                      balance=card.credit_balance,391                                                                      status="æ£å¸¸" if card.frozenstatus == 0 else "å»ç»"392                                                                      ), "INFORMATION")393                        confirm = common.input_msg("确认è¦å»ç»æ¤å¡å(y/n)?", ("y", "n"))394                        if confirm == "y":395                            card.frozenstatus = 1396                            card.update_card()397                            common.show_message("æ¤å¡å·²å»ç»!", "NOTICE")398                # éåº399                if _choose == "0":400                    quit_flag = True401        else:402            # 䏿¯ admin è§è²æ æé403            common.show_message("æéä¸å¤!", "ERROR")404    else:405        common.show_message("请å
ç»å½ç³»ç»!", "NOTICE")406        userobj.login()407if __name__ == "__main__":408    today = datetime.now().strftime("%Y-%m-%d")409    weekoftoday = date.weekday(datetime.now())410    curruser = Users()411    # åå§å对账å412    report.create_statement_main()413    # --------    å¼å§ä¸»ç¨åº   -------------------414    exitflag = False415    while not exitflag:416        # å¦æç¨æ·ç»å½äºï¼æ¾ç¤ºç»å½ççé¢; æªç»å½æ¾ç¤ºæªç»å½ççé¢417        if not curruser.islogin:418            print(templates.index_default_menu.format("", today, common.numtochr(weekoftoday)))419        else:...test_messageview.py
Source:test_messageview.py  
...30                                   usertypes.MessageLevel.error])31@pytest.mark.flaky  # on macOS32def test_single_message(qtbot, view, level):33    with qtbot.wait_exposed(view, timeout=5000):34        view.show_message(level, 'test')35    assert view._messages[0].isVisible()36def test_message_hiding(qtbot, view):37    """Messages should be hidden after the timer times out."""38    with qtbot.wait_signal(view._clear_timer.timeout):39        view.show_message(usertypes.MessageLevel.info, 'test')40    assert not view._messages41def test_size_hint(view):42    """The message height should increase with more messages."""43    view.show_message(usertypes.MessageLevel.info, 'test1')44    height1 = view.sizeHint().height()45    assert height1 > 046    view.show_message(usertypes.MessageLevel.info, 'test2')47    height2 = view.sizeHint().height()48    assert height2 == height1 * 249def test_word_wrap(view, qtbot):50    """A long message should be wrapped."""51    with qtbot.wait_signal(view._clear_timer.timeout):52        view.show_message(usertypes.MessageLevel.info, 'short')53        height1 = view.sizeHint().height()54        assert height1 > 055    text = ("Athene, the bright-eyed goddess, answered him at once: Father of "56            "us all, Son of Cronos, Highest King, clearly that man deserved to be "57            "destroyed: so let all be destroyed who act as he did. But my heart aches "58            "for Odysseus, wise but ill fated, who suffers far from his friends on an "59            "island deep in the sea.")60    view.show_message(usertypes.MessageLevel.info, text)61    height2 = view.sizeHint().height()62    assert height2 > height163    assert view._messages[0].wordWrap()64def test_show_message_twice(view):65    """Show the same message twice -> only one should be shown."""66    view.show_message(usertypes.MessageLevel.info, 'test')67    view.show_message(usertypes.MessageLevel.info, 'test')68    assert len(view._messages) == 169def test_show_message_twice_after_first_disappears(qtbot, view):70    """Show the same message twice after the first is gone."""71    with qtbot.wait_signal(view._clear_timer.timeout):72        view.show_message(usertypes.MessageLevel.info, 'test')73    # Just a sanity check74    assert not view._messages75    view.show_message(usertypes.MessageLevel.info, 'test')76    assert len(view._messages) == 177def test_changing_timer_with_messages_shown(qtbot, view, config_stub):78    """When we change messages.timeout, the timer should be restarted."""79    config_stub.val.messages.timeout = 900000  # 15s80    view.show_message(usertypes.MessageLevel.info, 'test')81    with qtbot.wait_signal(view._clear_timer.timeout):82        config_stub.val.messages.timeout = 10083@pytest.mark.parametrize('count, expected', [(1, 100), (3, 300),84                                             (5, 500), (7, 500)])85def test_show_multiple_messages_longer(view, count, expected):86    """When there are multiple messages, messages should be shown longer.87    There is an upper maximum to avoid messages never disappearing.88    """89    for message_number in range(1, count+1):90        view.show_message(usertypes.MessageLevel.info,91                          'test ' + str(message_number))92    assert view._clear_timer.interval() == expected93@pytest.mark.parametrize('replace1, replace2, length', [94    (None, None, 2),    # Two stacked messages95    ('testid', 'testid', 1),  # Two replaceable messages96    (None, 'testid', 2),  # Stacked and replaceable97    ('testid', None, 2),  # Replaceable and stacked98    ('testid1', 'testid2', 2),  # Different IDs99])100def test_replaced_messages(view, replace1, replace2, length):101    """Show two stack=False messages which should replace each other."""102    view.show_message(usertypes.MessageLevel.info, 'test', replace=replace1)103    view.show_message(usertypes.MessageLevel.info, 'test 2', replace=replace2)104    assert len(view._messages) == length105def test_replacing_different_severity(view):106    view.show_message(usertypes.MessageLevel.info, 'test', replace='testid')107    with pytest.raises(AssertionError):108        view.show_message(usertypes.MessageLevel.error, 'test 2', replace='testid')109def test_replacing_changed_text(view):110    view.show_message(usertypes.MessageLevel.info, 'test', replace='testid')111    view.show_message(usertypes.MessageLevel.info, 'test 2')112    view.show_message(usertypes.MessageLevel.info, 'test 3', replace='testid')113    assert len(view._messages) == 2114    assert view._messages[0].text() == 'test 3'115    assert view._messages[1].text() == 'test 2'116def test_replacing_geometry(qtbot, view):117    view.show_message(usertypes.MessageLevel.info, 'test', replace='testid')118    with qtbot.wait_signal(view.update_geometry):119        view.show_message(usertypes.MessageLevel.info, 'test 2', replace='testid')120@pytest.mark.parametrize('button, count', [121    (Qt.LeftButton, 0),122    (Qt.MiddleButton, 0),123    (Qt.RightButton, 0),124    (Qt.BackButton, 2),125])126def test_click_messages(qtbot, view, button, count):127    """Messages should disappear when we click on them."""128    view.show_message(usertypes.MessageLevel.info, 'test mouse click')129    view.show_message(usertypes.MessageLevel.info, 'test mouse click 2')130    qtbot.mousePress(view, button)...Arduino.py
Source:Arduino.py  
...20    arduino.port = '/dev/ttyUSB0' # para linux21def connect():22    result = False23    if arduino.is_open:24        terminal_messages.show_message('success', 'conexion exitosa.')25        result = {'option':'connect', 'value' : 'conexion exitosa.'}26    terminal_messages.show_message('info', 'abriendo conexion con arduino...')27    arduino.open()28    time.sleep(2)29    if arduino.is_open:30        terminal_messages.show_message('success', 'conexion exitosa.')31        result = {'option':'connect', 'value' : 'conexion exitosa.'}32    else:33        terminal_messages.show_message('error', 'conexion fallida.')34        result = {'option':'connect', 'value' : 'conexion fallida.'}35def disconnect():36    result = False37    terminal_messages.show_message('info', 'cerrando conexion con arduino...')38    if arduino.is_open:39        arduino.close()40        terminal_messages.show_message('success', 'conexion cerrada.')41        result = {'option':'disconnect', 'value' : 'conexion cerrada.'}42    else:43        result = {'option':'disconnect', 'value' : 'conexion cerrada.'}44    return result45def receive_data():46    if arduino.is_open:47        result = arduino.read(100)48        message = 'resultado : {}'.format(result)49        terminal_messages.show_message('debug', message)50        if not result:51            terminal_messages.show_message('error', 'no se recibio lectura.')52        else:53            message = 'mensaje recibido "{}"'.format(result)54            terminal_messages.show_message('success', message)55def read_line():56    if arduino.is_open:57        result = arduino.readline()58        message = 'resultado : {}'.format(result)59        terminal_messages.show_message('debug', message)60        if not result:61            terminal_messages.show_message('error', 'no se recibio lectura.')62        else:63            message = 'mensaje recibido "{}"'.format(result)64            terminal_messages.show_message('success', message)65def send_data(data):66    if arduino.is_open:67        message = 'enviando data "{}" a arduino...'.format(data)68        terminal_messages.show_message('info', message)69        arduino.write(data.encode())70''' recibe la orden para enviar a arduino y devuelve json con la respuesta '''71def send_order(data):72    result = False73    if arduino.is_open:74        message = 'enviando orden "{}" a arduino...'.format(data)75        terminal_messages.show_message('info', message)76        arduino.write(data.encode())77        time.sleep(1)78        result = arduino.readline()79        if not result or result == b'\r\n':80            terminal_messages.show_message('error', 'respuesta arduino vacia.')81            return {'option':'error', 'value':'respuesta arduino vacia.'}82        result = result.decode('utf-8').strip('\n')83        result = result.replace('\'','"')84        result = json.loads(result)85    else:86        result = {'option':'error', 'value' : 'se ha perdido la conexion con arduino'}87    terminal_messages.show_message('info', result)88    return result89def status():90    result = False91    if arduino.is_open:92        result = {'option':'status', 'value' : 'conectado'}93    else:94        result = {'option':'status', 'value' : 'desconectado'}...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
