Best Python code snippet using tappy_python
DemoMoudle.py
Source:DemoMoudle.py  
...38                id=model.id,39                age=model.age,40                birthday=model.birthday,41            ))42        return self.make_ok(dict(data=data))43    def post(self):44        body = self.parse_json({45            "type": "object",46            "properties": {47                "userInfo": {48                    "type": "object",49                    "properties": {50                        "name": {"type": "string"},51                        "age": {"type": "number"},52                        "birthday": {"type": "string"},53                    },54                    "required": [55                        "name",56                        "age",57                        "birthday"58                    ]59                }60            },61            "required": ["userInfo"]62        })63        with db.session.begin(subtransactions=True) as s:64            s.session.add(DemoObjectModel(**body))65        return self.make_ok()66    def put(self):67        """é坹忮µæ´æ°(key ä¸åå¨json object å¢å key)68        UPDATE demo_object69        set70        user_info = JSON_SET(user_info, '$.comment', '$comment')71        where72        JSON_EXTRACT(user_info, '$.name') = '$name';73        """74        body = self.parse_json({75            "type": "object",76            "properties": {77                "name": {"type": "string"},78                "comment": {"type": "string"}79            },80            "required": ["name"]81        })82        comment = body.get("comment", "")83        if not comment:84            return self.make_ok()85        DemoObjectModel.query.filter(86            DemoObjectModel.userInfo["name"] == body.get("name")87        ).update(88            {"userInfo": func.json_set(DemoObjectModel.userInfo, '$.comment', comment)},89            synchronize_session='fetch'90        )91        return self.make_ok()92    def delete(self):93        """å é¤json ä¸çæä¸ªkey94        æ¥è¯¢key æ¯å¦åå¨95        SELECT json_contains_path(`user_info`, 'all', '$.comment')  from `demo_object` WHERE96        JSON_EXTRACT(user_info, '$.name') = '$name';97        UPDATE demo_object set user_info = JSON_REMOVE(user_info, '$.commentâ)98        where JSON_EXTRACT(user_info, '$.name') = '$name';99        """100        body = self.parse_json({101            "type": "object",102            "properties": {103                "name": {"type": "string"},104                "key": {"type": "string"}105            },106            "required": ["name", "key"]107        })108        query_model = DemoObjectModel.query.filter(109            DemoObjectModel.userInfo["name"] == body.get("name")110        )111        key = body.get('key')112        is_has_keys = query_model.with_entities(113            func.json_contains_path(114                DemoObjectModel.userInfo,115                "all",116                f"$.{key}"117            ).label("exist")118        ).first().exist119        if is_has_keys:120            query_model.update(121                {"userInfo": func.json_remove(DemoObjectModel.userInfo, f'$.{key}')},122                synchronize_session='fetch'123            )124        return self.make_ok()125class DemoArrayHandler(ApiResource):126    """json array æä½127    æ ¹æ®school è·å major128    SELECT129    id,130    JSON_EXTRACT(edu_list,131    REPLACE(REPLACE(JSON_SEARCH(edu_list, 'all', 'å大'),'"',''),'.school','.major')) as major132    from demo_array;133    """134    def get(self):135        self.add_argument("school", type=str, location="args", required=True, help="school is required")136        args = self.parse_args()137        school = args.get("school", "")138        models = DemoArrayModel.query.filter().with_entities(139            DemoArrayModel.id,140            func.replace(141                func.json_extract(DemoArrayModel.eduList, func.replace(142                    func.replace(143                        func.json_search(144                            DemoArrayModel.eduList,145                            'all',146                            school147                        ), '"', ''148                    ), '.school', '.major')), '"', ''149            ).label("major")150        )151        data = []152        for model in models:153            data.append(dict(154                id=model.id,155                major=model.major156            ))157        return self.make_ok(dict(data=data))158    def post(self):159        body = self.parse_json(dict(160            type="object",161            properties=dict(162                properties=dict(163                    eduList=dict(164                        type="array",165                        items=dict(166                            type="object",167                            properties=dict(168                                school=dict(type="string"),169                                major=dict(type="string")170                            ),171                            required=["school", "major"]172                        )173                    )174                )175            ),176            required=["eduList"]177        ))178        with db.session.begin(subtransactions=True) as s:179            s.session.add(DemoArrayModel(**body))180        return self.make_ok()181    def put(self):182        """ ä¿®æ¹183        update demo_array184        set edu_list =185        JSON_REPLACE(edu_list, replace(JSON_SEARCH(edu_list, 'all', 'å京大å¦'), '"', ''), 'å大');186        """187        body = self.parse_json(dict(188            type="object",189            properties=dict(190                newSchool=dict(type="string"),191                oldSchool=dict(type="string")192            ),193            required=["newSchool", "oldSchool"]194        ))195        DemoArrayModel.query.filter().update(196            {"eduList": func.json_replace(197                DemoArrayModel.eduList,198                func.replace(199                    func.json_search(200                        DemoArrayModel.eduList,201                        'all',202                        body.get('oldSchool')203                    ),204                    '"',205                    ''206                ),207                body.get("newSchool")208            )},209            synchronize_session='fetch'210        )211        return self.make_ok()212    def delete(self):213        """æ ¹æ®school å é¤ major214        æ¥è¯¢key æ¯å¦åå¨215        SELECT JSON_CONTAINS_PATH(edu_list, 'one',216        REPLACE(JSON_SEARCH(edu_list, 'one', 'å大', null, '$**.school'),'"','')217        ) from demo_array;218        åå¨å é¤major key219        update demo_array set220        edu_list = JSON_REMOVE(221            edu_list,222            REPLACE(223                REPLACE(224                    JSON_SEARCH(225                        edu_list, 'one', 'å大'226                    ),227                '"',228                ''),229            '.school',230            '.major')231        ) where id=1;232        """233        models = DemoArrayModel.query.filter().with_entities(234            DemoArrayModel.id,235            func.json_contains_path(236                DemoArrayModel.eduList,237                'one',238                func.replace(239                    func.json_search(240                        DemoArrayModel.eduList,241                        'one',242                        'å大',243                        None,244                        '$**.school'245                    ), '"', ''246                )247            ).label("count")248        )249        exist_ids = []250        for model in models:251            if model.count:252                exist_ids.append(model.id)253        if exist_ids:254            DemoArrayModel.query.filter(255                DemoArrayModel.id.in_(exist_ids)256            ).update(257                {"eduList": func.json_remove(258                    DemoArrayModel.eduList,259                    func.replace(260                        func.replace(261                            func.json_search(262                                DemoArrayModel.eduList,263                                'all',264                                'å大'265                            ),266                            '"',267                            ''268                        ),269                        '.school',270                        '.major'271                    )272                )},273                synchronize_session='fetch'274            )...suite_tests.py
Source:suite_tests.py  
1#!/usr/bin/env python2"""Testing FoBiS.py"""3# import doctest4from __future__ import print_function5import filecmp6import os7import subprocess8import unittest9import sys10sys.path.append("../../main/python/")11from fobis.fobis import run_fobis12try:13  subprocess.call(["caf -v"])14  opencoarrays = True15except OSError as e:16  opencoarrays = False17class SuiteTest(unittest.TestCase):18  """Testing suite for FoBiS.py."""19  @staticmethod20  def run_build(directory):21    """22    Method for running the build function into a selected directory.23    Parameters24    ----------25    directory : str26      relative path to tested directory27    """28    print("Testing " + directory)29    build_ok = False30    old_pwd = os.getcwd()31    os.chdir(os.path.dirname(os.path.abspath(__file__)) + '/' + directory)32    run_fobis(fake_args=['clean', '-f', 'fobos'])33    try:34      run_fobis(fake_args=['build', '-f', 'fobos'])35      build_ok = os.path.exists(directory)36    except:37      if directory == 'build-test6':38        with open('building-errors.log') as logerror:39          build_ok = 'Unclassifiable statement' in list(logerror)[-1]40        os.remove('building-errors.log')41    run_fobis(fake_args=['rule', '-f', 'fobos', '-ex', 'finalize'])42    run_fobis(fake_args=['clean', '-f', 'fobos'])43    os.chdir(old_pwd)44    return build_ok45  @staticmethod46  def run_clean(directory):47    """48    Method for running the clean function into a selected directory.49    Parameters50    ----------51    directory : str52      relative path to tested directory53    """54    print("Testing " + directory)55    old_pwd = os.getcwd()56    os.chdir(os.path.dirname(os.path.abspath(__file__)) + '/' + directory)57    run_fobis(fake_args=['build', '-f', 'fobos'])58    run_fobis(fake_args=['clean', '-f', 'fobos'])59    clean_ok = not os.path.exists(directory)60    os.chdir(old_pwd)61    return clean_ok62  @staticmethod63  def make_makefile(directory):64    """65    Make makefile into a selected directory.66    Parameters67    ----------68    directory : str69      relative path to tested directory70    """71    print("Testing " + directory)72    make_ok = False73    old_pwd = os.getcwd()74    os.chdir(os.path.dirname(os.path.abspath(__file__)) + '/' + directory)75    run_fobis(fake_args=['build', '-f', 'fobos', '-m', 'makefile_check'])76    make_ok = filecmp.cmp('makefile_check', 'makefile_ok')77    if not make_ok:78      if os.path.exists('makefile_ok2'):79        make_ok = filecmp.cmp('makefile_check', 'makefile_ok2')80      if not make_ok:81        print('makefile generated')82        with open('makefile_check', 'r') as mk_check:83          print(mk_check.read())84    run_fobis(fake_args=['clean', '-f', 'fobos'])85    os.chdir(old_pwd)86    return make_ok87  @staticmethod88  def run_install(directory):89    """90    Run the install function into a selected directory.91    Parameters92    ----------93    directory : str94      relative path to tested directory95    """96    print("Testing " + directory)97    install_ok = False98    old_pwd = os.getcwd()99    os.chdir(os.path.dirname(os.path.abspath(__file__)) + '/' + directory)100    run_fobis(fake_args=['clean', '-f', 'fobos'])101    run_fobis(fake_args=['build', '-f', 'fobos'])102    run_fobis(fake_args=['install', '-f', 'fobos', '--prefix', 'prefix'])103    files = [os.path.join(dp, f) for dp, _, filenames in os.walk('./prefix/') for f in filenames]104    install_ok = len(files) > 0105    run_fobis(fake_args=['rule', '-f', 'fobos', '-ex', 'finalize'])106    run_fobis(fake_args=['clean', '-f', 'fobos'])107    os.chdir(old_pwd)108    return install_ok109  @staticmethod110  def run_doctest(directory):111    """112    Method for running the doctest function into a selected directory.113    Parameters114    ----------115    directory : str116      relative path to tested directory117    """118    print("Testing " + directory)119    doctest_ok = True120    old_pwd = os.getcwd()121    os.chdir(os.path.dirname(os.path.abspath(__file__)) + '/' + directory)122    run_fobis(fake_args=['clean', '-f', 'fobos'])123    run_fobis(fake_args=['doctests', '-f', 'fobos'])124    run_fobis(fake_args=['rule', '-f', 'fobos', '-ex', 'finalize'])125    run_fobis(fake_args=['clean', '-f', 'fobos'])126    os.chdir(old_pwd)127    return doctest_ok128  @staticmethod129  def run_rule(directory):130    """131    Run the rule function into a selected directory.132    Parameters133    ----------134    directory : str135      relative path to tested directory136    """137    print("Testing " + directory)138    rule_ok = False139    old_pwd = os.getcwd()140    os.chdir(os.path.dirname(os.path.abspath(__file__)) + '/' + directory)141    run_fobis(fake_args=['rule', '-ex', 'test'])142    rule_ok = True143    os.chdir(old_pwd)144    return rule_ok145  def test_buildings(self):146    """Test buildings."""147    num_failures = 0148    failed = []149    passed = []150    for test in range(28):151      if test + 1 == 15 and not opencoarrays:152        continue153      build_ok = self.run_build('build-test' + str(test + 1))154      if not build_ok:155        failed.append('FAILED build-test' + str(test + 1))156        num_failures += 1157      else:158        passed.append('PASSED build-test' + str(test + 1))159    print('List of PASSED build-tests')160    for pas in passed:161      print(pas)162    if len(failed) > 0:163      print('List of FAILED build-tests')164      for fail in failed:165        print(fail)166    self.assertEquals(num_failures, 0)167    return168  def test_cleanings(self):169    """Test cleanings."""170    num_failures = 0171    failed = []172    passed = []173    for test in range(1):174      clean_ok = self.run_clean('clean-test' + str(test + 1))175      if not clean_ok:176        failed.append('FAILED clean-test' + str(test + 1))177        num_failures += 1178      else:179        passed.append('PASSED clean-test' + str(test + 1))180    print('List of PASSED clean-tests')181    for pas in passed:182      print(pas)183    if len(failed) > 0:184      for fail in failed:185        print(fail)186    self.assertEquals(num_failures, 0)187    return188  def test_makefile(self):189    """Test makefile generation."""190    num_failures = 0191    failed = []192    passed = []193    for test in range(2):194      make_ok = self.make_makefile('makefile-test' + str(test + 1))195      if not make_ok:196        failed.append('FAILED makefile-test' + str(test + 1))197        num_failures += 1198      else:199        passed.append('PASSED makefile-test' + str(test + 1))200    print('List of PASSED makefile-tests')201    for pas in passed:202      print(pas)203    if len(failed) > 0:204      for fail in failed:205        print("Error: Test " + fail + " failed!")206    self.assertEquals(num_failures, 0)207    return208  def test_installs(self):209    """Test installs."""210    num_failures = 0211    failed = []212    passed = []213    for test in range(4):214      install_ok = self.run_install('install-test' + str(test + 1))215      if not install_ok:216        failed.append('FAILED install-test' + str(test + 1))217        num_failures += 1218      else:219        passed.append('PASSED install-test' + str(test + 1))220    print('List of PASSED install-tests')221    for pas in passed:222      print(pas)223    if len(failed) > 0:224      for fail in failed:225        print(fail)226    self.assertEquals(num_failures, 0)227    return228  def test_doctests(self):229    """Test doctests."""230    num_failures = 0231    failed = []232    passed = []233    for test in range(3):234      build_ok = self.run_doctest('doctest-test' + str(test + 1))235      if not build_ok:236        failed.append('FAILED doctest-test' + str(test + 1))237        num_failures += 1238      else:239        passed.append('PASSED doctest-test' + str(test + 1))240    print('List of PASSED doctest-tests')241    for pas in passed:242      print(pas)243    if len(failed) > 0:244      for fail in failed:245        print(fail)246    self.assertEquals(num_failures, 0)247    return248  def test_rules(self):249    """Test rules."""250    num_failures = 0251    failed = []252    passed = []253    for test in range(1):254      rule_ok = self.run_rule('rule-test' + str(test + 1))255      if not rule_ok:256        failed.append('FAILED rule-test' + str(test + 1))257        num_failures += 1258      else:259        passed.append('PASSED rule-test' + str(test + 1))260    print('List of PASSED rule-tests')261    for pas in passed:262      print(pas)263    if len(failed) > 0:264      for fail in failed:265        print(fail)266    self.assertEquals(num_failures, 0)267    return268if __name__ == "__main__":...q2.py
Source:q2.py  
...26list_question_mark = lambda l : (True) if (empty_question_mark(l)) else ((list_question_mark(l[1])) if (issubclass(type(l), tuple)) else (False)) 27dict_question_mark = lambda d : (False) if ((not list_question_mark(d))) else ((False) if (empty_question_mark(d)) else (((d[0] == L3String("dictend"))) if ((issubclass(type(d[0]), tuple) == False)) else (dict_question_mark(d[1])))) 28empty_dict_question_mark = lambda dict : (False) if ((not dict_question_mark(dict))) else ((not issubclass(type(dict[0]), tuple))) 29get_rec = lambda dict, k : (make_error(L3String("Key not found"))) if (empty_dict_question_mark(dict)) else ((dict[0][1]) if ((dict[0][0] == k)) else (get_rec(dict[1], k))) 30get = lambda dict, k : (make_error(L3String("Error: not a dictionary"))) if ((not dict_question_mark(dict))) else ((get_rec(dict, k)) if (error_question_mark(get_rec(dict, k))) else (make_ok(get_rec(dict, k)))) 31put_rec = lambda dict, k, v : (L3List(dict[0], (k , v), L3String("dictend"))) if (empty_dict_question_mark(dict[1])) else ((((k , v) , dict[1])) if ((dict[0][0][1] == k)) else ((dict[0] , put_rec(dict[1], k, v)))) 32put = lambda dict, k, v : (make_error(L3String("Error: not a dictionary"))) if ((not dict_question_mark(dict))) else ((make_ok(L3List((k , v), L3String("dictend")))) if (empty_dict_question_mark(dict)) else ((make_ok(((k , v) , dict[1]))) if ((dict[0][0] == k)) else (make_ok(put_rec(dict, k, v))))) 33map_dict_rec = lambda new_dict, old_dict_iter, f : (map_dict_rec(result__val(put(new_dict, old_dict_iter[0][0], f(old_dict_iter[0][1]))), old_dict_iter[1], f)) if (issubclass(type(old_dict_iter[0]), tuple)) else (new_dict) 34map_dict = lambda dict, f : make_ok(map_dict_rec(make_dict(), dict, f)) 35filter_dict_rec = lambda new_dict, old_dict_iter, pred : (new_dict) if (empty_dict_question_mark(old_dict_iter)) else ((filter_dict_rec(result__val(put(new_dict, old_dict_iter[0][0], old_dict_iter[0][1])), old_dict_iter[1], pred)) if (pred(old_dict_iter[0][0], old_dict_iter[0][1])) else (filter_dict_rec(new_dict, old_dict_iter[1], pred))) ...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!!
