Best Python code snippet using Testify_python
manille.py
Source:manille.py  
1################################################################################2#Implements a simple text based version of the card game Manie3#4#This is a 4 person trick based card game 5import operator6import random7import pdb 8    9#Some Constants10kNumPlayers = 411kSuites = ["H","S","C","D"]12#In Manille the card order is not traditional, this dictionary maps the13#rank of a card vs it's display type14ranks = {0:'    8 ',15         1:'    7 ',16         2:'    9 ',17         3:' Jack ',18         4:'Queen ',19         5:' King ',20         6:'  Ace ',21         7:'   10 '}22#similar mapping but using the image name indexes for the GUI23rankIcon ={0:'08',24           1:'07',25           2:'09',26           3:'11',27           4:'12',28           5:'13',29           6:'01',30           7:'10'}31suites = {'H':'Hearts',32          'S':'Spades',33          'C':'Clubs',34          'D':'Diamonds'}35#Define an object to hold:36#  rank37#  suite38#  score value39# of each card40#41#Define:42# comparison43# string display44class Card:45    trump_suite =''46    suite_led   =''47    def __init__ (self, suite, rank):48        self.suite=suite49        self.rank=rank50        self.score=051        if (self.rank>2):52            self.score = self.rank - 253            54    def __str__ (self):55        #use the dictonaries to create a display string for printing56        return ranks[self.rank] + 'of ' + suites[self.suite]57    def __lt__ (self, other):58        # Should return a negative integer if self < other,59        # zero if self == other, a positive integer if self > other.60        #61        # Comparison accoring to the rules fo Manille:62        #  Trump suite is higher than any card in any other suite,63        #  rank within the trump suite determines which is greater64        #65        #  Any card that is not in the suite which was lead can not win66        #67        #  If there is no trump, rank within the suite which was lead68        #  determines which is greater69        if self.suite == Card.suite_led:70            if other.suite == Card.suite_led:71                return self.rank < other.rank72            elif other.suite == Card.trump_suite:73                return True74            else:75                return False76        elif self.suite == Card.trump_suite:77            if other.suite == Card.trump_suite:78                return self.rank < other.rank79            else:80                return False81        else:82            return True83    84#define a colleciton of cards85class Deck:86    def __init__ (self):87        #one card for each rank in each suite88        self.cards = [Card (rank=r,suite=s) for s in kSuites89                      for r in range(len(ranks))]90    def shuffle(self):91        random.shuffle(self.cards)92        93#define a player class with a basic AI        94class Player:95    def __init__(self):96        #keep track of current hand97        self.cards = []98        #keep trak of tricks won99        self.tricks = []100        #keep track of score across hands101        self.score = 0102    #build the current had during the deal103    def add_card(self, card):104        self.cards.append(card);105        106    #clear all the tricks collected for scoring at the end of hand107    def new_hand(self):108        self.tricks = []109    110    #sort the hand by suite and rank for ease of human player111    def sort_hand(self):112        self.cards = sorted(self.cards,key=lambda x: (x.suite, -x.rank))113    #provide a simple AI function which choses the trup suite if the114    #players is the dealer for the hand - uses the trivial heuristic of115    #which suite is the longest116    def chose_trump(self):117        nMax=0118        max_suite=''119        for s in kSuites:120            n=0121            for c in self.cards:122                if c.suite==s:123                    n += 1124            if n>nMax:125                max_suite=s126                nMax=n127        #set the trump suite on the card class128        Card.trump_suite=max_suite129    #Pick a card to open a trick130    #131    # There are no restrictions on card to be selected.132    #133    # AI is trivial and will select highest ranked card. This will134    # tend to clear out the trump suite fast!135    def open_trick(self):136        #select the card to play137        play = max(enumerate(self.cards), key = operator.itemgetter(1))[0]138        #return the selected card and remove it from the hand139        return self.cards.pop(play)140    #Determine the legal moves given the player's hand and the current141    #state of the trick142    #143    #rules which apply:144    #145    #  a player must follow suite if they can146    # 147    #  if the player's partener is not already winning the trick and148    #  the player has the option to win the trick they MUST do so149    # 150    def legal_moves(self, trick):151        #collect the cards that are in the suite which was lead152        in_suite = [i for i,c in enumerate(self.cards) if c.suite == trick[0].suite]153        #check who is winning and if we must win154        trick_win = max(enumerate(trick),key = operator.itemgetter(1))[0]155        must_win=True156        if len(trick)==2 and trick_win==0:157            must_win=False158        elif len(trick)==3 and trick_win==1:159            must_win=False160        #Apply rules161        if len(in_suite)>0:162            #we have cards in the lead suite163            if must_win:164                #we are required to win, so check if we can165                legal = [i for i in in_suite166                         if self.cards[i]>trick[trick_win]]167                if (len(legal)==0):168                    #could not win but must follow suite169                    legal=in_suite170            else:171                #parterner has hand, but we must follow suite172                legal = in_suite173        else:174            #we are void of suite175            if must_win:176                #check our hand for winning trump cards177                legal = [i for i,c in enumerate(self.cards)178                         if c > trick[trick_win]]179                if (len(legal)==0):180                    #can't win...play any181                    legal = list(range(len(self.cards)))182            else:183                #not required to win...play any184                legal = list(range(len(self.cards)))185        return legal186    #play a card which follows the rules with a simple AI to win if we187    #can and play the lowest card if we can't188    def play_card(self,trick):189        in_suite = list(filter(lambda c: c.suite == Card.suite_led,190                               self.cards))191        if (len(in_suite)>0):192            #required to play in suite193            max_card = max(in_suite)194            if any([card > max_card for card in trick]):195                #Best card in suite can't win, throw out the lowest196                min_card = min(in_suite)197                return self.cards.pop(self.cards.index(min_card))198            return self.cards.pop(self.cards.index(max_card))199        else:200            #no cards in suite201            in_trump = list(filter(lambda c: c.suite == Card.trump_suite,self.cards))202            if len(in_trump)>0:203                #todo - choose the trump smarter204                max_trump = max(in_trump)205                return self.cards.pop(self.cards.index(max_trump))206            else:207                #no trump cards no cards in suite208                #throw out lowest card209                smallest =  min(self.cards)210                return self.cards.pop(self.cards.index(smallest))211    #Add a trick the stack of winnings212    def take_trick(self,trick):213        self.tricks.append(trick)214    #count the points in the tricks won215    def score_tricks(self):216        hand_score=0217        for t in self.tricks:218            for c in t:219                hand_score+=c.score220        self.score += hand_score221        return hand_score222#Derive from the Player class and provide a command line UI for card selection    223class HumanPlayer(Player):224    #Allow user to pick any card to play225    def open_trick(self):226        #print a list of all the cards with the selection index to the left227        for i,c in enumerate(self.cards):228            print('{:>2d}'.format(i)+" "+str(c))229        #prompt for input230        n = int(input("Pick a card to lead the trick (trump is " + Card.trump_suite +")"))231        #require the input to be valid232        while not n in range(len(self.cards)):233            n = int(input ("Try again!:"))234        #remove the card from the hand and return it235        return self.cards.pop(n)236    #Allow user to pick a legal card to play237    def play_card(self,trick):238        #display the current state of the trick for the player to follow239        print("")240        print("Trick so far:")241        #find the current winner to highlight with a *242        max_idx = max(enumerate(trick), key=operator.itemgetter(1))[0]243        for i,c in enumerate(trick):244            if(i==max_idx):245                print(str(c) + " *")246            else:247                print(c)248        #determine the possible legal moves given the hand and state of the trick249        legal=self.legal_moves(trick)250        #print a list of all the cards with the selection index to the left legal moves251        #are highlighted with an @ symbol252        print("\nPlayer Hand:")253        for i,c in enumerate(self.cards):254            if i in legal:255                print('{:>2d}'.format(i)+" "+str(c)+ " @")256            else:257                print('{:>2d}'.format(i)+" "+str(c))258        #prompt for input and require it to be valid259        n = int(input("Pick a card to play (trump is " + Card.trump_suite +")"))260        while not n in legal:261            n = int(input ("Try again!:"))262        return self.cards.pop(n)263#manage the state of the game264class Game:265    def __init__(self):266        self.deck = []267        self.lead_player =0268        self.dealer=0269        #create 3 AI players and 1 humman270        self.players = []271        for i in range(3):272            self.players.append(Player())273        self.players.append(HumanPlayer())274    #create a set of cards and distribut them to teh players275    #this is done at the start of each hand276    def deal(self):277        self.deck = Deck()278        self.deck.shuffle()279        ncards = len(self.deck.cards)280        for p in self.players:281            p.new_hand()282            for c in range(ncards//4):283                p.add_card(self.deck.cards.pop())284            p.sort_hand()285    #play out a single trick by getting a card from each player and286    #determining the winning player287    def play_trick(self):288        #have the lead player pick any card and make the selected289        #card define the lead suite290        trick = [self.players[self.lead_player].open_trick()]291        Card.suite_led = trick[0].suite292        #have each of the following players follow suite293        for p in [(x + self.lead_player + 1)%4 for x in range(3)]:294            card = self.players[p].play_card(trick)295            trick.append(card)296        #determine the winner and have them take the trick297        winner = max(enumerate(trick), key=operator.itemgetter(1))[0]298        winner += self.lead_player299        winner %= 4300        self.players[winner].take_trick(trick)301        return (trick,winner)302    #play through a hand of manille, deal and run through all the tricks303    def play_hand(self):304        #have the dealer chose the trump card305        self.players[self.dealer].chose_trump()306        #set the dealer to be the first player307        self.lead_player = self.dealer308        self.dealer += 1309        #play through all the tricks310        while(len(self.players[0].cards)>0):311            trick,winner = self.play_trick()312            for i,c in enumerate(trick):313                print("Player " + str(1+((self.lead_player+i)%4))314                      + " " + str(c))315            print ("Player " + str(1+winner) + " takes trick")316            print ("")317            self.lead_player = winner318        #display the scores319        print("Hand Ends")320        for i,p in enumerate(self.players):321            p.score_tricks()322            print ("Player "+ str(i+1) + " score " + str(p.score))323def RUNIT():324    g=Game()325    g.deal()326    g.play_hand()327            328if __name__ == "__main__":                329    RUNIT()...base_test.py
Source:base_test.py  
1import time2from xyTest.base.base_object import OBase3from xyTest.base.config_base import CONFIG_BASE4from xyTest.util.file_operation import OPERATION_FILE5from xyTest.util.format_operation import OPERATION_FORMAT6class TestBase(OBase):7    8    """9    """10                            11    def __init__(self, 12                 name=None, 13                 typ=None,14                 suite=None,15                 *args, **kwargs):16        OBase.__init__(self,17                       name=name,18                       *args, **kwargs)19        if typ:20            self.type = typ21        else:22            self.type ='qa'23        self.running_device = None24        self.waiting_time = None  # After current case, waiting before next case25        self.suite = suite26        self.clenaup_variable()27        self.clenaup_test()28        self.set_default_variable()29        30    # ------------------------------------------------31    # get and set ---32    # ------------------------------------------------33    def before_test_run(self): pass34    def after_test_run(self): pass35    def create_case(self, name, dic): pass36    def set_selected_case(self, value): pass37        38    def get_case_all(self): return self.case_all39    def set_case_all(self, value): 40        self.clenaup_variable()41        42        if (not isinstance(value, dict)) or (not OPERATION_FILE.is_true(value)):43            self.message_command(self, "Error", "Wrong value in set_case_all - value= " + str(value))44            return45        case_dic = {}46        for k, v in value.items():47            case = self.create_case(k, v)48            case_dic[k] = case49            self.list_all_case.append(case)50        self.case_all = case_dic51        CONFIG_BASE.dic_object_case[self.suite]=case_dic52        self.list_all_case.sort(key=lambda x: x.name.lower(), reverse=False)53        self.list_selected_case = self.list_all_case54#         print ("self.case_all = ", self.case_all)55#         print ("self.list_all_case = ", self.list_all_case)56        57    def set_test_running(self):58        self.name_running  = OPERATION_FORMAT.test_running_name(self.name)59        self.name_log_folder = "%s_%s" % (self.suite, self.name_running)60        self.path_category_log = OPERATION_FILE.set_test_log_folder(self.name_log_folder)61#         print ("self.name_log_folder = ", self.name_log_folder)  #  =  suite_and_2018-09-26-15-00-23_onawhim62        63    def clenaup_variable(self):64        # re start test65        self.case_all = {}66        self.list_all_case = []67        self.list_selected_case = []68        69    def clenaup_test(self):70        # this test71        self.name_running = None72        self.time_this_run = None73        self.is_run = False # this test does not run so far74        self.is_submitted = False   # the test result does not submit so far75        76        # add report info77        self.report_list_locked_case = []78        self.report_list_good_case = []79        self.report_list_bad_case = []80        self.lst_att_zip = []81        82    def set_default_variable(self):83#         print ("CONFIG_BASE.dic_lib_category = ", CONFIG_BASE.dic_lib_category)84#         print ("self.name = ", self.name)85        self.category_config = CONFIG_BASE.dic_lib_category[self.name]['config']86#         print ("tesrt Section = ", self.category_config.sections())  #  ['api', 'qa', 'dev']87        self.dic_config = {}88        89#         print ("self.category_config  =", self.category_config)90        if self.category_config:91            for se in self.category_config.options(self.type):92                self.dic_config[se] = OPERATION_FILE.try_one_option(self.category_config, self.type, se)93        #94        this_version = OPERATION_FILE.get_key_value(self.dic_config, 'version')95        if this_version:96            self.version = this_version97        else:98            self.version = 'unknown_version'99        self.default_pre_name = self.type + "_" + self.version 100        101        102    # ------------------------------------------------103    # run test ---104    # ------------------------------------------------105    def before_next_case(self):106        if self.waiting_time:107            wt = self.waiting_time108            self.waiting_time = None109            print ("waiting for %s seconds, - " % (str(wt))) # then call - before_test_run110            time.sleep(wt)111            self.before_test_run()112        113    def run_test(self):114        self.debug(["Start Test - ", self.name])115        self.set_test_running()116        try:117            self.before_test_run()118            print ("\n--------------------------------------------------------------------")119            msg= "--- Begin %s - test %s. --- in test.run_test() ---" % (self.suite, self.name_running)120            self.add_log_message('test', msg)121            print ("--------------------------------------------------------------------\n")122            self.time_start = time.time()123            124            for case in self.list_selected_case:125                self.before_next_case()126                if case.locked:127                    self.report_list_locked_case.append(case)128                else:129                    case.start_test()130                    self.check_run_case(case)131                    132            OPERATION_FILE.set_suite_log_file(CONFIG_BASE)133            self.time_end = time.time()134            self.time_this_run = self.get_time_run() #<class 'float'>135            print ("\n--------------------------------------------------------------------")136            msg= "--- End %s - test %s in %s Seconds. ---" % (self.suite, self.name_running, str((self.time_this_run)))137            self.is_run = True138            self.add_log_message('test', msg)139            print ("--------------------------------------------------------------------\n")140            self.after_test_run()141            142        except Exception as e:143            self.message_command(self, "Exception", "Running test "+self.name, e)144            pass145        146        147        148    def check_run_case(self, case):149        case.analysis_record()150        if case.locked:151            self.report_list_locked_case.append(case)152        elif case.status:153            self.report_list_good_case.append(case)154        else:155            self.report_list_bad_case.append(case)156            157#         print ("self.report_list_bad_case = ", self.report_list_bad_case)158    # ------------------------------------------------159    # before test, setup variables ---160    # ------------------------------------------------161    def get_jmeter_server_option(self, sec='jmeter'):162        in_suite = CONFIG_BASE.session_config163        try:164            opts = []165            if in_suite.has_section(sec):166                for key in in_suite[sec]:  167                    if 'jmeter_H' in key:168                        tt = '-H ' + in_suite[sec][key]169                    elif 'jmeter_P' in key:170                        tt = '-P ' + in_suite[sec][key]171                    else:172                        tt = '-J%s=%s' % (key, in_suite[sec][key])173                    opts.append(tt)174            if opts:175                return ' '.join(opts)176            else:177                return False178        except:179            return False180    def get_rest_server_option(self):181        in_suite = CONFIG_BASE.session_config182        try:183            lst_sec = ['rest', 'db']184            for sec in lst_sec:185                if in_suite.has_section(sec):186                    for key in in_suite[sec]:  187                        OPERATION_FILE.pass_one_config_option(in_suite, sec, key, self, sec+key)188                else:189                    self.message_command(self, "Error", "No REST -%s- Info in suite config file" % sec)190                    return False191        except Exception as e:192            self.message_command(self, "Exception", "in REST Test - def get_rest_server_option-", e)193            return False194        195    def check_appium_config(self, opt, sec='constant'):196        in_suite = CONFIG_BASE.session_config197        in_config = CONFIG_BASE.config_appium198        result = False199        try:200            if opt:201                result = OPERATION_FILE.try_one_option(in_suite, sec, opt)202                if not result:203                    result = OPERATION_FILE.try_one_option(in_config, sec, opt)204                return  result205            else:206                config = False207                if in_suite.has_section(sec):208                    config = in_suite209                else:210                    if in_config.has_section(sec):211                        config = in_config212                if config:213                    dic_option = dict(config.items(sec))214                    return dic_option215                216                return False217        except:218            return False219    def check_appium_driver(self, driver):220        type_driver = str(type(driver)).lower()221        if 'appium.webdriver.' in type_driver:222            return True223        return False224    225    # ------------------------------------------------226    # info and report ---227    # ------------------------------------------------228    229    def add_log_message(self, level, ms='No-Message'):230        self.message_command(self, level, ms)231#         if self.has_log:232#             from xyTest.log.constant import post_log_message, TEST_LOG233#             post_log_message(TEST_LOG, level, ms)...__init__.py
Source:__init__.py  
1# Copyright 2011 Google Inc.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7#      http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14from __future__ import absolute_import15import exceptions16import os17import re18import traceback19import unittest20from util import *21_debug_mode = False22class DebuggerTestCase(unittest.TestCase):23  def __init__(self,progname):24    self._progname = progname25  def setUp(self):26    self._debugger = Debugger()27    self._proc = self._debugger.launch_suspended(self._progname)28  @property29  def debugger(self):30    return self._debugger31  @property32  def process(self):33    return self._progname34def test_is_selected(in_testnames, testname):35#  toks = test_name.split(".")36  for tn in in_testnames:37    if re.search(tn, testname):38      return True39  return False40###########################################################################41class NdbVerboseTestResult(unittest.TestResult):42  def addError(self,test,err):43    traceback.print_tb(err[2])44    unittest.TestResult.addError(self,test,err)45    print err[1]46    if _debug_mode:47      print "*** Halting test due to error. ***"48      os._exit(0) # do this so we truly exit... even if we have a lingering thread [eew]49  def addFailure(self,test,err):50    traceback.print_tb(err[2])51    unittest.TestResult.addFailure(self,test,err)52    print err[1]53    if _debug_mode:54      print "*** Halting test due to error. ***"55      os._exit(0) # do this so we truly exit... even if we have a lingering thread [eew]56def set_debug_mode(halt):57  if not isinstance(halt, bool):58    raise TypeError("Expected bool")59  global _debug_mode60  _debug_mode = halt61###########################################################################62def do_run(testnames = None):63  """64  Run a test given a list of test regexps to run, or all tests.65  """66  immediate = _debug_mode67  MessageLoop.set_in_test_mode(True)68  dirs = ["tests", "tests/util", "tests/debugger", "tests/progdb"]69  try:70    import ui71    dirs.append("tests/ui")72  except:73    pass74  v = 275  r = unittest.TextTestRunner(verbosity=v)76  l = unittest.TestLoader()77  for dir in dirs:78    dirname = os.path.join(".", dir)79    files = os.listdir(dirname)80    pyfiles = [d for d in files if os.path.splitext(d)[1] == ".py"]81    if "__init__.py" in pyfiles:82      pyfiles.remove("__init__.py")83    suite = unittest.TestSuite()84    for pyfile in pyfiles:85      if pyfile.startswith("."):86        continue # dotfiles87      modbase = dir.replace("/",".")88      modname = os.path.splitext(pyfile)[0]89      pymodule = "%s.%s" % (modbase, modname)90      try:91        module = __import__(pymodule,fromlist=[True])92      except:93        print "While importing [%s]\n" % pymodule94        traceback.print_exc()95        continue96      try:97        if hasattr(module,"load_tests"):98          s = module.load_tests()99        else:100          s = unittest.TestLoader().loadTestsFromModule(module)101      except Exception, ex:102        raise Exception("Error loading test cases from %s: %s"% (pymodule, str(ex)))103      for t in s:104        if isinstance(t, unittest.TestSuite):105          for i in t:106            if testnames != None:107              if test_is_selected(testnames,i.id()):108                suite.addTest(i)109            else:110              suite.addTest(i)111        elif isinstance(t, unittest.TestCase):112          if testnames != None:113            if test_is_selected(testnames,t.id()):114              suite.addTest(t)115          else:116            suite.addTest(t)117        else:118          raise Exception("Wtf, expected TestSuite or TestCase, got %s" % t)119    if suite.countTestCases():120      if immediate == False:121        log0_raw("Test for %s", dir)122        log0_raw("----------------------------------------------------------------------")123        r.run(suite)124        log0_raw("\n")125        log0_raw("\n")126      else:127        for case in suite:128          tr = NdbVerboseTestResult()129          log0_raw("----------------------------------------------------------------------")130          log0_raw("%s", case.id())131          case.run(result=tr)132          if tr.wasSuccessful():133            log0("OK\n")134          elif len(tr.errors):135            log0("Error\n")136          else:137            log0("Fail\n")138    log2("TestSystem: done with module %s", dir)139  log2("TestSystem: done with all ymodules")140def run(testnames = None):141  try:142    do_run(testnames)143  finally:144    MessageLoop.quit(True)145    MessageLoop.set_in_test_mode(False)146# Stray code to load tests from a list of classes:147def _load_tests_from_class(cls):148  in_suite = unittest.TestLoader().loadTestsFromTestCase(case)149  assert(isinstance(suite,unittest.TestSuite))150  for test in in_suite:151    tests.addTest(test)152def _append_suite_to_suite(dst_suite,src_suite):153  for test in src_suite:...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!!
