Best Python code snippet using avocado_python
cryptoconditions.py
Source:cryptoconditions.py  
...10import time11from decimal import Decimal12def assert_success(result):13    assert_equal(result['result'], 'success')14def assert_error(result):15    assert_equal(result['result'], 'error')16class CryptoConditionsTest (BitcoinTestFramework):17    def setup_chain(self):18        print("Initializing CC test directory "+self.options.tmpdir)19        self.num_nodes = 120        initialize_chain_clean(self.options.tmpdir, self.num_nodes)21    def setup_network(self, split = False):22        print("Setting up network...")23        self.addr    = "RWPg8B91kfK5UtUN7z6s6TeV9cHSGtVY8D"24        self.pubkey  = "02676d00110c2cd14ae24f95969e8598f7ccfaa675498b82654a5b5bd57fc1d8cf"25        self.privkey = "UqMgxk7ySPNQ4r9nKAFPjkXy6r5t898yhuNCjSZJLg3RAM4WW1m9"26        self.nodes   = start_nodes(self.num_nodes, self.options.tmpdir,27                    extra_args=[[28                    # always give -ac_name as first extra_arg29                    '-ac_name=REGTEST',30                    '-conf='+self.options.tmpdir+'/node0/REGTEST.conf',31                    '-port=64367',32                    '-rpcport=64368',33                    '-regtest',34                    '-addressindex=1',35                    '-spentindex=1',36                    '-ac_supply=5555555',37                    '-ac_reward=10000000',38                    '-pubkey=' + self.pubkey,39                    '-ac_cc=2',40                    '-whitelist=127.0.0.1',41                    '-debug',42                    '-daemon',43                    '-rpcuser=rt',44                    '-rpcpassword=rt'45                    ]]46        )47        self.is_network_split = split48        self.rpc              = self.nodes[0]49        self.sync_all()50        print("Done setting up network")51    def send_and_mine(self, xtn):52        txid = self.rpc.sendrawtransaction(xtn)53        assert txid, 'got txid'54        # we need the tx above to be confirmed in the next block55        self.rpc.generate(1)56        return txid57    def run_faucet_tests(self):58        rpc = self.rpc59        # basic sanity tests60        result = rpc.getwalletinfo()61        assert_greater_than(result['txcount'], 100)62        assert_greater_than(result['balance'], 0.0)63        balance = result['balance']64        faucet  = rpc.faucetaddress()65        assert_equal(faucet['result'], 'success')66        # verify all keys look like valid AC addrs, could be better67        for x in ['myCCaddress', 'FaucetCCaddress', 'Faucetmarker', 'myaddress']:68            assert_equal(faucet[x][0], 'R')69        result  = rpc.faucetaddress(self.pubkey)70        assert_success(result)71        # test that additional CCaddress key is returned72        for x in ['myCCaddress', 'FaucetCCaddress', 'Faucetmarker', 'myaddress', 'CCaddress']:73            assert_equal(result[x][0], 'R')74        # no funds in the faucet yet75        result = rpc.faucetget()76        assert_error(result)77        result = rpc.faucetinfo()78        assert_success(result)79        result = rpc.faucetfund("0")80        assert_error(result)81        result = rpc.faucetfund("-1")82        assert_error(result)83        # we need at least 1 + txfee to get84        result = rpc.faucetfund("2")85        assert_success(result)86        assert result['hex'], "hex key found"87        # broadcast the xtn88        result = rpc.sendrawtransaction(result['hex'])89        txid   = result[0]90        assert txid, "found txid"91        # we need the tx above to be confirmed in the next block92        rpc.generate(1)93        result   = rpc.getwalletinfo()94        balance2 =  result['balance']95        # make sure our balance is less now96        assert_greater_than(balance, balance2)97        result = rpc.faucetinfo()98        assert_success(result)99        assert_greater_than( result['funding'], 0 )100        result = rpc.faucetget()101        assert_success(result)102        assert result['hex'], "hex key found"103        # try to broadcast the xtn, but we will get 'faucet is only for brand new addresses'104        assert_raises(JSONRPCException, rpc.sendrawtransaction, [ result['hex'] ])105        newaddr = rpc.getnewaddress()106        assert newaddr, "got a new address"107        result  = rpc.validateaddress(newaddr)108        newpubkey = result['pubkey']109        assert newpubkey, "got a pubkey for new address"110    def run_dice_tests(self):111        rpc     = self.nodes[0]112        dice  = rpc.diceaddress()113        assert_equal(dice['result'], 'success')114        for x in ['myCCaddress', 'DiceCCaddress', 'Dicemarker', 'myaddress']:115            assert_equal(dice[x][0], 'R')116        dice  = rpc.diceaddress(self.pubkey)117        assert_equal(dice['result'], 'success')118        for x in ['myCCaddress', 'DiceCCaddress', 'Dicemarker', 'myaddress', 'CCaddress']:119            assert_equal(dice[x][0], 'R')120        # no dice created yet121        result  = rpc.dicelist()122        assert_equal(result, [])123        # creating dice plan with too long name (>8 chars)124        result = rpc.dicefund("THISISTOOLONG", "10000", "10", "10000", "10", "5")125        assert_error(result)126        # creating dice plan with < 100 funding127        result = rpc.dicefund("LUCKY","10","1","10000","10","5")128        assert_error(result)129        # creating dice plan with 0 blocks timeout130        result = rpc.dicefund("LUCKY","10","1","10000","10","0")131        assert_error(result)132        # creating dice plan133        dicefundtx  = rpc.dicefund("LUCKY","1000","1","800","10","5")134        diceid = self.send_and_mine(dicefundtx['hex'])135        # checking if it in plans list now136        result = rpc.dicelist()137        assert_equal(result[0], diceid)138        # set dice name for futher usage139        dicename = "LUCKY"140        # adding zero funds to plan141        result = rpc.diceaddfunds(dicename,diceid,"0")142        assert_error(result)143        # adding negative funds to plan144        result = rpc.diceaddfunds(dicename,diceid,"-1")145        assert_error(result)146        # adding funds to plan147        addfundstx = rpc.diceaddfunds(dicename,diceid,"1100")148        result = self.send_and_mine(addfundstx['hex'])149        # checking if funds added to plan150        result = rpc.diceinfo(diceid)151        assert_equal(result["funding"], "2100.00000000")152        # not valid dice info checking153        result = rpc.diceinfo("invalid")154        assert_error(result)155        # placing 0 amount bet156        result = rpc.dicebet(dicename,diceid,"0","1")157        assert_error(result)158        # placing negative amount bet159        result = rpc.dicebet(dicename,diceid,"-1","1")160        assert_error(result)161        # placing bet more than maxbet162        result = rpc.dicebet(dicename,diceid,"900","1")163        assert_error(result)164        # placing bet with amount more than funding165        result = rpc.dicebet(dicename,diceid,"3000","1")166        assert_error(result)167        # placing bet with potential won more than funding168        result = rpc.dicebet(dicename,diceid,"750","9")169        assert_error(result)170        # placing 0 odds bet171        result = rpc.dicebet(dicename,diceid,"1","0")172        assert_error(result)173        # placing negative odds bet174        result = rpc.dicebet(dicename,diceid,"1","-1")175        assert_error(result)176        # placing bet with odds more than allowed177        result = rpc.dicebet(dicename,diceid,"1","11")178        assert_error(result)179        # placing bet with not correct dice name180        result = rpc.dicebet("nope",diceid,"100","1")181        assert_error(result)182        # placing bet with not correct dice id183        result = rpc.dicebet(dicename,self.pubkey,"100","1")184        assert_error(result)185        # valid bet placing186        placebet = rpc.dicebet(dicename,diceid,"100","1")187        betid = self.send_and_mine(placebet["hex"])188        assert result, "bet placed"189        # check bet status190        result = rpc.dicestatus(dicename,diceid,betid)191        assert_success(result)192        # have to make some entropy for the next test193        entropytx = 0194        fundingsum = 1195        while entropytx < 10:196             fundingsuminput = str(fundingsum)197             fundinghex = rpc.diceaddfunds(dicename,diceid,fundingsuminput)198             result = self.send_and_mine(fundinghex['hex'])199             entropytx = entropytx + 1200             fundingsum = fundingsum + 1201        rpc.generate(2)202        # note initial dice funding state at this point.203        # TODO: track player balance somehow (hard to do because of mining and fees)204        diceinfo = rpc.diceinfo(diceid)205        funding = float(diceinfo['funding'])206        # placing  same amount bets with amount 1 and odds  1:2, checking if balance changed correct207        losscounter = 0208        wincounter = 0209        betcounter = 0210        while (betcounter < 10):211            placebet = rpc.dicebet(dicename,diceid,"1","1")212            betid = self.send_and_mine(placebet["hex"])213            finish = rpc.dicefinish(dicename,diceid,betid)214            self.send_and_mine(finish["hex"])215            betresult = rpc.dicestatus(dicename,diceid,betid)216            betcounter = betcounter + 1217            if betresult["status"] == "loss":218                losscounter = losscounter + 1219            elif betresult["status"]  == "win":220                wincounter = wincounter + 1221        # funding balance should increase if player loss, decrease if player won222        fundbalanceguess = funding + losscounter - wincounter223        fundinfoactual = rpc.diceinfo(diceid)224        assert_equal(round(fundbalanceguess),round(float(fundinfoactual['funding'])))225    def run_token_tests(self):226        rpc    = self.nodes[0]227        result = rpc.tokenaddress()228        assert_success(result)229        for x in ['AssetsCCaddress', 'myCCaddress', 'Assetsmarker', 'myaddress']:230            assert_equal(result[x][0], 'R')231        result = rpc.tokenaddress(self.pubkey)232        assert_success(result)233        for x in ['AssetsCCaddress', 'myCCaddress', 'Assetsmarker', 'myaddress', 'CCaddress']:234            assert_equal(result[x][0], 'R')235        # there are no tokens created yet236        result = rpc.tokenlist()237        assert_equal(result, [])238        # trying to create token with negaive supply239        result = rpc.tokencreate("NUKE", "-1987420", "no bueno supply")240        assert_error(result)241        # creating token with name more than 32 chars242        result = rpc.tokencreate("NUKE123456789012345678901234567890", "1987420", "name too long")243        assert_error(result)244        # creating valid token245        result = rpc.tokencreate("DUKE", "1987.420", "Duke's custom token")246        assert_success(result)247        tokenid = self.send_and_mine(result['hex'])248        result = rpc.tokenlist()249        assert_equal(result[0], tokenid)250        # there are no token orders yet251        result = rpc.tokenorders()252        assert_equal(result, [])253        # getting token balance for pubkey254        result = rpc.tokenbalance(self.pubkey)255        assert_success(result)256        assert_equal(result['balance'], 0)257        assert_equal(result['CCaddress'], 'RCRsm3VBXz8kKTsYaXKpy7pSEzrtNNQGJC')258        assert_equal(result['tokenid'], self.pubkey)259        # get token balance for token with pubkey260        result = rpc.tokenbalance(tokenid, self.pubkey)261        assert_success(result)262        assert_equal(result['balance'], 198742000000)263        assert_equal(result['tokenid'], tokenid)264        # get token balance for token without pubkey265        result = rpc.tokenbalance(tokenid)266        assert_success(result)267        assert_equal(result['balance'], 198742000000)268        assert_equal(result['tokenid'], tokenid)269        # this is not a valid assetid270        result = rpc.tokeninfo(self.pubkey)271        assert_error(result)272        # check tokeninfo for valid token273        result = rpc.tokeninfo(tokenid)274        assert_success(result)275        assert_equal(result['tokenid'], tokenid)276        assert_equal(result['owner'], self.pubkey)277        assert_equal(result['name'], "DUKE")278        assert_equal(result['supply'], 198742000000)279        assert_equal(result['description'], "Duke's custom token")280        # invalid numtokens ask281        result = rpc.tokenask("-1", tokenid, "1")282        assert_error(result)283        # invalid numtokens ask284        result = rpc.tokenask("0", tokenid, "1")285        assert_error(result)286        # invalid price ask287        result = rpc.tokenask("1", tokenid, "-1")288        assert_error(result)289        # invalid price ask290        result = rpc.tokenask("1", tokenid, "0")291        assert_error(result)292        # invalid tokenid ask293        result = rpc.tokenask("100", "deadbeef", "1")294        assert_error(result)295        # valid ask296        tokenask = rpc.tokenask("100", tokenid, "7.77")297        tokenaskhex = tokenask['hex']298        tokenaskid = self.send_and_mine(tokenask['hex'])299        result = rpc.tokenorders()300        order = result[0]301        assert order, "found order"302        # invalid ask fillunits303        result = rpc.tokenfillask(tokenid, tokenaskid, "0")304        assert_error(result)305        # invalid ask fillunits306        result = rpc.tokenfillask(tokenid, tokenaskid, "-777")307        assert_error(result)308        # valid ask fillunits309        fillask = rpc.tokenfillask(tokenid, tokenaskid, "777")310        result = self.send_and_mine(fillask['hex'])311        txid   = result[0]312        assert txid, "found txid"313        # should be no token orders314        result = rpc.tokenorders()315        assert_equal(result, [])316        # checking ask cancellation317        testorder = rpc.tokenask("100", tokenid, "7.77")318        testorderid = self.send_and_mine(testorder['hex'])319        cancel = rpc.tokencancelask(tokenid, testorderid)320        self.send_and_mine(cancel["hex"])321        result = rpc.tokenorders()322        assert_equal(result, [])323        # invalid numtokens bid324        result = rpc.tokenbid("-1", tokenid, "1")325        assert_error(result)326        # invalid numtokens bid327        result = rpc.tokenbid("0", tokenid, "1")328        assert_error(result)329        # invalid price bid330        result = rpc.tokenbid("1", tokenid, "-1")331        assert_error(result)332        # invalid price bid333        result = rpc.tokenbid("1", tokenid, "0")334        assert_error(result)335        # invalid tokenid bid336        result = rpc.tokenbid("100", "deadbeef", "1")337        assert_error(result)338        tokenbid = rpc.tokenbid("100", tokenid, "10")339        tokenbidhex = tokenbid['hex']340        tokenbidid = self.send_and_mine(tokenbid['hex'])341        result = rpc.tokenorders()342        order = result[0]343        assert order, "found order"344        # invalid bid fillunits345        result = rpc.tokenfillbid(tokenid, tokenbidid, "0")346        assert_error(result)347        # invalid bid fillunits348        result = rpc.tokenfillbid(tokenid, tokenbidid, "-777")349        assert_error(result)350        # valid bid fillunits351        fillbid = rpc.tokenfillbid(tokenid, tokenbidid, "1000")352        result = self.send_and_mine(fillbid['hex'])353        txid   = result[0]354        assert txid, "found txid"355        # should be no token orders356        result = rpc.tokenorders()357        assert_equal(result, [])358        # checking bid cancellation359        testorder = rpc.tokenbid("100", tokenid, "7.77")360        testorderid = self.send_and_mine(testorder['hex'])361        cancel = rpc.tokencancelbid(tokenid, testorderid)362        self.send_and_mine(cancel["hex"])363        result = rpc.tokenorders()364        assert_equal(result, [])365        # invalid token transfer amount (have to add status to CC code!)366        randompubkey = "021a559101e355c907d9c553671044d619769a6e71d624f68bfec7d0afa6bd6a96"367        result = rpc.tokentransfer(tokenid,randompubkey,"0")368        assert_error(result)369        # invalid token transfer amount (have to add status to CC code!)370        result = rpc.tokentransfer(tokenid,randompubkey,"-1")371        assert_error(result)372        # valid token transfer373        sendtokens = rpc.tokentransfer(tokenid,randompubkey,"1")374        self.send_and_mine(sendtokens["hex"])375        result = rpc.tokenbalance(tokenid,randompubkey)376        assert_equal(result["balance"], 1)377    def run_rewards_tests(self):378        rpc     = self.nodes[0]379        result = rpc.rewardsaddress()380        for x in ['RewardsCCaddress', 'myCCaddress', 'Rewardsmarker', 'myaddress']:381            assert_equal(result[x][0], 'R')382        result = rpc.rewardsaddress(self.pubkey)383        for x in ['RewardsCCaddress', 'myCCaddress', 'Rewardsmarker', 'myaddress', 'CCaddress']:384            assert_equal(result[x][0], 'R')385        # no rewards yet386        result = rpc.rewardslist()387        assert_equal(result, [])388        # looking up non-existent reward should return error389        result = rpc.rewardsinfo("none")390        assert_error(result)391        # creating rewards plan with name > 8 chars, should return error392        result = rpc.rewardscreatefunding("STUFFSTUFF", "7777", "25", "0", "10", "10")393        assert_error(result)394        # creating rewards plan with 0 funding395        result = rpc.rewardscreatefunding("STUFF", "0", "25", "0", "10", "10")396        assert_error(result)397        # creating rewards plan with 0 maxdays398        result = rpc.rewardscreatefunding("STUFF", "7777", "25", "0", "10", "0")399        assert_error(result)400        # creating rewards plan with > 25% APR401        result = rpc.rewardscreatefunding("STUFF", "7777", "30", "0", "10", "10")402        assert_error(result)403        # creating valid rewards plan404        result = rpc.rewardscreatefunding("STUFF", "7777", "25", "0", "10", "10")405        assert result['hex'], 'got raw xtn'406        fundingtxid = rpc.sendrawtransaction(result['hex'])407        assert fundingtxid, 'got txid'408        # confirm the above xtn409        rpc.generate(1)410        result = rpc.rewardsinfo(fundingtxid)411        assert_success(result)412        assert_equal(result['name'], 'STUFF')413        assert_equal(result['APR'], "25.00000000")414        assert_equal(result['minseconds'], 0)415        assert_equal(result['maxseconds'], 864000)416        assert_equal(result['funding'], "7777.00000000")417        assert_equal(result['mindeposit'], "10.00000000")418        assert_equal(result['fundingtxid'], fundingtxid)419        # checking if new plan in rewardslist420        result = rpc.rewardslist()421        assert_equal(result[0], fundingtxid)422        # creating reward plan with already existing name, should return error423        result = rpc.rewardscreatefunding("STUFF", "7777", "25", "0", "10", "10")424        assert_error(result)425        # add funding amount must be positive426        result = rpc.rewardsaddfunding("STUFF", fundingtxid, "-1")427        assert_error(result)428        # add funding amount must be positive429        result = rpc.rewardsaddfunding("STUFF", fundingtxid, "0")430        assert_error(result)431        # adding valid funding432        result = rpc.rewardsaddfunding("STUFF", fundingtxid, "555")433        addfundingtxid = self.send_and_mine(result['hex'])434        assert addfundingtxid, 'got funding txid'435        # checking if funding added to rewardsplan436        result = rpc.rewardsinfo(fundingtxid)437        assert_equal(result['funding'], "8332.00000000")438        # trying to lock funds, locking funds amount must be positive439        result = rpc.rewardslock("STUFF", fundingtxid, "-5")440        assert_error(result)441        # trying to lock funds, locking funds amount must be positive442        result = rpc.rewardslock("STUFF", fundingtxid, "0")443        assert_error(result)444        # trying to lock less than the min amount is an error445        result = rpc.rewardslock("STUFF", fundingtxid, "7")446        assert_error(result)447        # locking funds in rewards plan448        result = rpc.rewardslock("STUFF", fundingtxid, "10")449        assert_success(result)450        locktxid = result['hex']451        assert locktxid, "got lock txid"452        # locktxid has not been broadcast yet453        result = rpc.rewardsunlock("STUFF", fundingtxid, locktxid)454        assert_error(result)455        # broadcast xtn456        txid = rpc.sendrawtransaction(locktxid)457        assert txid, 'got txid from sendrawtransaction'458        # confirm the xtn above459        rpc.generate(1)460        # will not unlock since reward amount is less than tx fee461        result = rpc.rewardsunlock("STUFF", fundingtxid, locktxid)462        assert_error(result)463    def run_test (self):464        print("Mining blocks...")465        rpc     = self.nodes[0]466        # utxos from block 1 become mature in block 101467        rpc.generate(101)468        self.sync_all()469        # this corresponds to -pubkey above470        print("Importing privkey")471        rpc.importprivkey(self.privkey)472#       self.run_faucet_tests()473        self.run_rewards_tests()474        self.run_dice_tests()475        self.run_token_tests()476        self.run_faucet_tests()...pyunit_typechecks.py
Source:pyunit_typechecks.py  
...9                                  assert_is_type, assert_matches, assert_satisfies)10# noinspection PyUnresolvedReferences,PyClassHasNoInit11def test_asserts():12    """Test type-checking functionality."""13    def assert_error(*args, **kwargs):14        """Check that assert_is_type() with given arguments throws an error."""15        try:16            assert_is_type(*args, **kwargs)17            raise RuntimeError("Failed to throw an exception")18        except H2OTypeError as exc:19            # Check whether the message can stringify properly20            message = str(exc)21            assert len(message) < 100022            return23    class A(object):24        """Dummy A."""25    class B(A):26        """Dummy B."""27    class C(A):28        """Dummy C."""29    class D(B, C):30        """Dummy D."""31    assert_is_type(3, int)32    assert_is_type(2**100, int)33    assert_is_type("3", str)34    assert_is_type(u"3", str)35    assert_is_type("foo", u"foo")36    assert_is_type(u"foo", "foo")37    assert_is_type("I", *list("ABCDEFGHIJKL"))38    assert_is_type(False, bool)39    assert_is_type(43, str, bool, int)40    assert_is_type(4 / 3, int, float)41    assert_is_type(None, None)42    assert_is_type(None, A, str, None)43    assert_is_type([], [float])44    assert_is_type([1, 4, 5], [int])45    assert_is_type([1.0, 2, 5], [int, float])46    assert_is_type([[2.0, 3.1, 0], [2, 4.4, 1.1], [-1, 0]], [[int, float]])47    assert_is_type([1, None, 2], [int, float, None])48    assert_is_type({1, 5, 1, 1, 3}, {int})49    assert_is_type({1, "hello", 3}, {int, str})50    assert_is_type({"foo": 1, "bar": 2}, {str: int})51    assert_is_type({"foo": 3, "bar": [5], "baz": None}, {str: U(int, None, [int])})52    assert_is_type({"foo": 1, "bar": 2}, {"foo": int, "bar": U(int, float, None), "baz": bool})53    assert_is_type({}, {"spam": int, "egg": int})54    assert_is_type({"spam": 10}, {"spam": int, "egg": int})55    assert_is_type({"egg": 1}, {"spam": int, "egg": int})56    assert_is_type({"egg": 1, "spam": 10}, {"spam": int, "egg": int})57    assert_is_type({"egg": 1, "spam": 10}, Dict(egg=int, spam=int))58    assert_is_type({"egg": 1, "spam": 10}, Dict(egg=int, spam=int, ham=U(int, None)))59    assert_is_type((1, 3), (int, int))60    assert_is_type(("a", "b", "c"), (int, int, int), (str, str, str))61    assert_is_type((1, 3, 4, 7, 11, 18), Tuple(int))62    assert_is_type((1, 3, "spam", 3, "egg"), Tuple(int, str))63    assert_is_type([1, [2], [{3}]], [int, [int], [{3}]])64    assert_is_type(A(), None, A)65    assert_is_type(B(), None, A)66    assert_is_type(C(), A, B)67    assert_is_type(D(), I(A, B, C))68    assert_is_type(A, type)69    assert_is_type(B, lambda aa: issubclass(aa, A))70    for a in range(-2, 5):71        assert_is_type(a, -2, -1, 0, 1, 2, 3, 4)72    assert_is_type(1, numeric)73    assert_is_type(2.2, numeric)74    assert_is_type(1, I(numeric, object))75    assert_is_type(34, I(int, NOT(0)))76    assert_is_type(["foo", "egg", "spaam"], [I(str, NOT("spam"))])77    assert_is_type(H2OFrame(), h2oframe)78    assert_is_type([[2.0, 3.1, 0], [2, 4.4, 1.1], [-1, 0, 0]],79                   I([[numeric]], lambda v: all(len(vi) == len(v[0]) for vi in v)))80    assert_is_type([None, None, float('nan'), None, "N/A"], [None, "N/A", I(float, math.isnan)])81    assert_error(3, str)82    assert_error(0, float)83    assert_error("Z", *list("ABCDEFGHIJKL"))84    assert_error(u"Z", "a", "...", "z")85    assert_error("X", u"x")86    assert_error(0, bool)87    assert_error(0, float, str, bool, None)88    assert_error([1, 5], [float])89    assert_error((1, 3), (int, str), (str, int), (float, float))90    assert_error(A(), None, B)91    assert_error(A, A)92    assert_error(A, lambda aa: issubclass(aa, B))93    assert_error(135, I(int, lambda x: 0 <= x <= 100))94    assert_error({"foo": 1, "bar": "2"}, {"foo": int, "bar": U(int, float, None)})95    assert_error(3, 0, 2, 4)96    assert_error(None, numeric)97    assert_error("sss", numeric)98    assert_error(B(), I(A, B, C))99    assert_error(2, I(int, str))100    assert_error(0, I(int, NOT(0)))101    assert_error(None, NOT(None))102    assert_error((1, 3, "2", 3), Tuple(int))103    assert_error({"spam": 10}, Dict(spam=int, egg=int))104    assert_error({"egg": 5}, Dict(spam=int, egg=int))105    assert_error(False, h2oframe, pandas_dataframe, numpy_ndarray)106    assert_error([[2.0, 3.1, 0], [2, 4.4, 1.1], [-1, 0]],107                 I([[numeric]], lambda v: all(len(vi) == len(v[0]) for vi in v)))108    try:109        # Cannot use `assert_error` here because typechecks module cannot detect args in (*args, *kwargs)110        assert_is_type(10000000, I(int, lambda port: 1 <= port <= 65535))111        assert False, "Failed to throw an exception"112    except H2OTypeError as e:113        assert "integer & 1 <= port <= 65535" in str(e), "Bad error message: '%s'" % e114    url_regex = r"^(https?)://((?:[\w-]+\.)*[\w-]+):(\d+)/?$"115    assert_matches("Hello, world!", r"^(\w+), (\w*)!$")116    assert_matches("http://127.0.0.1:3233/", url_regex)117    m = assert_matches("https://localhost:54321", url_regex)118    assert m.group(1) == "https"119    assert m.group(2) == "localhost"120    assert m.group(3) == "54321"...test_forms.py
Source:test_forms.py  
...15        self.form_data.pop("page")16        self.assert_field_value("page", 1)17    def test_invalid_page(self):18        self.form_data["page"] = "0"19        self.assert_error("page", "Ensure this value is greater than or equal to 1.")20    def test_missing_page_size(self):21        self.form_data.pop("page_size")22        self.assert_field_value("page_size", 10)23    def test_zero_page_size(self):24        self.form_data["page_size"] = "0"25        self.assert_error("page_size", "Ensure this value is greater than or equal to 1.")26    def test_excessive_page_size(self):27        self.form_data["page_size"] = "101"28        self.assert_field_value("page_size", 100)29@ddt.ddt30class ThreadListGetFormTest(FormTestMixin, PaginationTestMixin, TestCase):31    """Tests for ThreadListGetForm"""32    FORM_CLASS = ThreadListGetForm33    def setUp(self):34        super(ThreadListGetFormTest, self).setUp()35        self.form_data = QueryDict(36            urlencode(37                {38                    "course_id": "Foo/Bar/Baz",39                    "page": "2",40                    "page_size": "13",41                }42            ),43            mutable=True44        )45    def test_basic(self):46        form = self.get_form(expected_valid=True)47        self.assertEqual(48            form.cleaned_data,49            {50                "course_id": CourseLocator.from_string("Foo/Bar/Baz"),51                "page": 2,52                "page_size": 13,53                "topic_id": set(),54                "text_search": "",55                "following": None,56                "view": "",57                "order_by": "last_activity_at",58                "order_direction": "desc",59            }60        )61    def test_topic_id(self):62        self.form_data.setlist("topic_id", ["example topic_id", "example 2nd topic_id"])63        form = self.get_form(expected_valid=True)64        self.assertEqual(65            form.cleaned_data["topic_id"],66            {"example topic_id", "example 2nd topic_id"},67        )68    def test_text_search(self):69        self.form_data["text_search"] = "test search string"70        form = self.get_form(expected_valid=True)71        self.assertEqual(72            form.cleaned_data["text_search"],73            "test search string",74        )75    def test_missing_course_id(self):76        self.form_data.pop("course_id")77        self.assert_error("course_id", "This field is required.")78    def test_invalid_course_id(self):79        self.form_data["course_id"] = "invalid course id"80        self.assert_error("course_id", "'invalid course id' is not a valid course id")81    def test_empty_topic_id(self):82        self.form_data.setlist("topic_id", ["", "not empty"])83        self.assert_error("topic_id", "This field cannot be empty.")84    def test_following_true(self):85        self.form_data["following"] = "True"86        self.assert_field_value("following", True)87    def test_following_false(self):88        self.form_data["following"] = "False"89        self.assert_error("following", "The value of the 'following' parameter must be true.")90    @ddt.data(*itertools.combinations(["topic_id", "text_search", "following"], 2))91    def test_mutually_exclusive(self, params):92        self.form_data.update({param: "True" for param in params})93        self.assert_error(94            "__all__",95            "The following query parameters are mutually exclusive: topic_id, text_search, following"96        )97    def test_invalid_view_choice(self):98        self.form_data["view"] = "not_a_valid_choice"99        self.assert_error("view", "Select a valid choice. not_a_valid_choice is not one of the available choices.")100    def test_invalid_sort_by_choice(self):101        self.form_data["order_by"] = "not_a_valid_choice"102        self.assert_error(103            "order_by",104            "Select a valid choice. not_a_valid_choice is not one of the available choices."105        )106    def test_invalid_sort_direction_choice(self):107        self.form_data["order_direction"] = "not_a_valid_choice"108        self.assert_error(109            "order_direction",110            "Select a valid choice. not_a_valid_choice is not one of the available choices."111        )112class CommentListGetFormTest(FormTestMixin, PaginationTestMixin, TestCase):113    """Tests for CommentListGetForm"""114    FORM_CLASS = CommentListGetForm115    def setUp(self):116        super(CommentListGetFormTest, self).setUp()117        self.form_data = {118            "thread_id": "deadbeef",119            "endorsed": "False",120            "page": "2",121            "page_size": "13",122        }123    def test_basic(self):124        form = self.get_form(expected_valid=True)125        self.assertEqual(126            form.cleaned_data,127            {128                "thread_id": "deadbeef",129                "endorsed": False,130                "page": 2,131                "page_size": 13132            }133        )134    def test_missing_thread_id(self):135        self.form_data.pop("thread_id")136        self.assert_error("thread_id", "This field is required.")137    def test_missing_endorsed(self):138        self.form_data.pop("endorsed")...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!!
