Best Python code snippet using ATX
user_management.py
Source:user_management.py  
1# -*- coding: utf-8 -*-2import webapp23import logging4from request_handlers import request_utils5import user_model6from constants import error_definitions, constants7import json8import ConfigParser9import datetime10#TODO remove global loggers?11logger = logging.getLogger()12        13class UserRequestsHandler(webapp2.RequestHandler):14    15    def post(self, api_method):16        try:17            resp = None18            if api_method == "set":19                logger.info("update user")20                update_json = json.loads(self.request.body)21                22                cookie = self.request.cookies.get(constants.cookie_key)23                user = user_model.user_by_cookie(cookie)24                resp = user.resp()25            if api_method == "upload_userpic":26                logger.info("upload_userpic")27            28            if resp:29                self.response.headers.add_header("Content-Type", "application/json")30                self.response.out.write(resp)31                32        except Exception, err:33            request_utils.out_error(self.response, err, 400, 400)34import endpoints35from User import message36def check_auth_success(user, app_install, is_new_user):37    # It's not possible to create a user and an app_install in transaction as it's redundant38    # to set them common parent (so I cannot make an ancestor query, so if it fails cleanup 39    # and return an error    40    if user and app_install:41        return user.to_message(app_install)42    if not user and app_install:43        app_install.key.delete()44        raise endpoints.BadRequestException("Fail to create user")45    if user and not app_install:46        if is_new_user:47            # If it was an auth with a new user we should remove the user entity (without 48            # AppInstallation user will not be able to login - so it have to re-register in any case49            user.key.delete()50        raise endpoints.BadRequestException("Fail to create app_install")51    raise endpoints.BadRequestException("Fail to create user and app_install")52def auth(request):53    logger.info("Authentication request")54    login_info = user_model.LoginInfoItem.from_message(request) #55    logger.info("login_info %s"%login_info)56    57    if len(login_info.login) < 3: 58        raise endpoints.BadRequestException(error_definitions.msg_wrong_login)59    if len(login_info.device_id) == 0:60        raise endpoints.BadRequestException(error_definitions.msg_wrong_device_id)61    62    logger.info("user_by_login")63    user = user_model.user_by_login(login_info.login)64    65    logger.info("user_by_login %s"%user)66    if (user):67        app_install = user_model.user_installation(user, login_info.device_id)68        logger.info("app_install= %s (%s)"%(app_install, login_info.device_id))69        error_text = None70        if not app_install:71            error_text = user.validate_password(login_info.password)72        else:73            logger.info("user with the login&device_id was already logged in - it is normal to \74                login without password from the same device (%s)"%app_install)75        76        if error_text:77            raise endpoints.BadRequestException(error_text)78        else:79            app_install = user_model.create_installation(user, login_info.device_id,80                                                         login_info.device_token, app_install)81            return check_auth_success(user, app_install, False)82    else:83        logger.info("Going to create a user")84        user, app_install = user_model.create_user_from_login_info(login_info)85        return check_auth_success(user, app_install, True)86        87    88def logout(request):89    logger.info("Logout does nothing now. Before it removed the cookie from request, but it is not necessary any more")90    91def password_tools(request):92    logger.info("tools request")93    cookie = request.cookie94    logger.info("cookie = %s"%cookie)95    user = user_model.user_by_cookie(cookie)96    tools = message.Tools()97    if user.email and len(user.email) > 0:98        tools.email = user.email99    pushable_installations = []100    for inst in user_model.user_app_installations(user):101        if inst.device_token and len (inst.device_token) > 0:102            pushable_installations.append(request_utils.human_datetime(inst.date))103    if len(pushable_installations) > 0:104        tools.push = pushable_installations105    return tools106def password_request(request):107    logger.info("request password")108    cookie = request.session.cookie109    logger.info("cookie = %s"%cookie)110    user = user_model.user_by_cookie(cookie)111    112    result = user.send_password(request.tool)113    resp = message.Tools()114    setattr(resp, request.tool, result)115    return resp116def user_update(request):117    cookie = request.session.cookie118    installation = user_model.installation_by_cookie(cookie)119    user = user_model.user_by_installation(installation)120    121    # if a region for user wasn't really set yet (only region was set), we have to use a region 122    # from config file (to insert to database)123    124    if request and request.region:125        regionlist = None 126        if not request.region.name:127            regionlist = region_list(request.region.id, None, None)128        if not request.region.id:129            logger.info("Strange situation: request.region.id is None, but request.region!=None")130            regionlist = region_list(constants.default_region, None, None)131        if regionlist:132            request.region = regionlist.possible_region133    user.set_properties(request)134    return user.to_message(installation)135def region_list(region_id, latitude, longitude):136    import math137    config_file='./resources/regions_config.cfg'138    parser = ConfigParser.RawConfigParser()139    parser.read(config_file)140        141    regionlist = message.RegionList()142    nearest_region = None143    min_distanse = -1144    for section in parser.sections():145        region = message.Region()146        region.id = section147        unicode_content = parser.get(section, "name").decode('utf-8')148        region.name = unicode_content 149        region.latitude = float(parser.get(section, "latitude"))150        region.longitude = float(parser.get(section, "longitude"))151        regionlist.regions.append(region)152        if region_id and region_id.lower() == section.lower():153            regionlist.possible_region = region154        else :155            if latitude and longitude:156                distanse = math.hypot(region.latitude - latitude, region.longitude - longitude)157                if min_distanse < 0 or distanse < min_distanse:158                    min_distanse = distanse 159                    nearest_region = region160    if not regionlist.possible_region and nearest_region:161        regionlist.possible_region = nearest_region162    return regionlist163def request_region_list(request):164    return region_list(request.id, request.latitude, request.longitude)165from Forecast import message as ForecastMessage166def utc_today():167    today = datetime.date.today()168    today_time = datetime.datetime(today.year, today.month, today.day)169    logger.info("today_time = %s"%str(today_time))170    return today_time171def calculate_next_update_time(current_time):172    config_file='./resources/forecast_settings.cfg'173    parser = ConfigParser.RawConfigParser()174    parser.read(config_file)175    today_time = utc_today()176    logger.info("current_time %s"%str(current_time))177    for section in parser.sections():178        startHour = int(parser.get(section, "startHour"))179        startMinute = int(parser.get(section, "startMinute"))180        refreshPeriod = int(parser.get(section, "refreshPeriod"))181        182        next_period_start = today_time + datetime.timedelta(hours=startHour, minutes=startMinute)183        logger.info("check period %s"%next_period_start)184        if current_time < next_period_start:185            logger.info("period found %s"%str(next_period_start))186            return next_period_start187        elif current_time < next_period_start + datetime.timedelta(minutes=refreshPeriod):188            logger.info("in refreshPeriod, forecast updates are possible, check a minute later")189            logger.info("%s"%str(current_time + datetime.timedelta(minutes=1)))190            return current_time + datetime.timedelta(minutes=1)191    logger.info("the last period in current day is checked, use first period of next day")192    startHour = int(parser.get("UpdateTime0", "startHour"))193    startMinute = int(parser.get("UpdateTime0", "startMinute"))194    return today_time+datetime.timedelta(days=1, hours=startHour, minutes=startMinute)195def test_calculate_next_update_time():196    logger.info("forecasts")197    today_time = utc_today()198    logger.info("UTC 00:00")199    calculate_next_update_time(today_time)200    logger.info("UTC 04:00")201    calculate_next_update_time(today_time+datetime.timedelta(hours=4))202    logger.info("UTC 04:50")203    calculate_next_update_time(today_time+datetime.timedelta(hours=4, minutes=50))204    logger.info("UTC 12:00")205    calculate_next_update_time(today_time+datetime.timedelta(hours=12))206    logger.info("UTC 24:00")207    calculate_next_update_time(today_time+datetime.timedelta(hours=24))208    209    logger.info("Current time %s (%s)"%(datetime.datetime.now(), datetime.datetime.utcnow()))210    calculate_next_update_time(datetime.datetime.utcnow())211    212def get_user_forecasts(request):213    logger.info("get_user_forecasts")214    user = user_model.user_by_cookie(request.cookie)215    216    next_update_time = calculate_next_update_time(datetime.datetime.utcnow())217    region = constants.default_region 218    if user and user.region:219        region = user.region.id 220    else:221        logger.info("No user region found - use default one")222        223    user.forecast_get_time = datetime.datetime.now()224    user.put()225    return ForecastMessage.get_region_spots(region, next_update_time)226    227forecast_top_max_count = 10228def get_user_spots_rating(request):229    230    logger.info("get_user_top_spots")231    user = user_model.user_by_cookie(request.cookie)232    233    user_ratings = user_model.SpotRatingItem.get_user_top_ratings(user)234    235    region_ratings = user_model.SpotRatingItem.get_top_ratings(user, forecast_top_max_count)236    237    #Filter out duplicates: 238    ratings_messages_by_spot = {}239    for rating in user_ratings+region_ratings:240        if not ratings_messages_by_spot.get(rating.spot_id):241            ratings_messages_by_spot[rating.spot_id] = rating.to_message()242    ratings_messages = ratings_messages_by_spot.values()243    if len(ratings_messages) > 10:244        ratings_messages = ratings_messages[:forecast_top_max_count]245    246    return ForecastMessage.SpotRatingList(ratings = ratings_messages)247def add_status(request):248    logger.info("add_user_status")249    #print "add_user_status", request250    cookie = request.session.cookie251    logger.info("cookie = %s"%cookie)252    user = user_model.user_by_cookie(cookie)253    254    msg = str([request.status_date, request.status, request.spot.id, request.user_region_id])255    logger.info("debug data %s"%msg)256        257    if (not request.status_date or not request.status or not request.spot.id or  258            not request.user_region_id):259        raise endpoints.BadRequestException(error_definitions.msg_wrong_parameters)260    261    last_status_item = user_model.UserStatusItem.get_last_user_spot_status(request, user)262    263    new_status_item = user_model.UserStatusItem.from_message(request, user)264    265    if new_status_item.status != constants.kStatusNone: #No need to calculate rating for messages266        user_model.SpotRatingItem.update_rating_with_status(new_status_item, last_status_item)267    new_status_item.put()268    269    270def get_user_status_list(request):271    logger.info("user_status_list")272    cookie = request.cookie273    logger.info("cookie = %s"%cookie)274    user = user_model.user_by_cookie(cookie)275    status_list = user_model.UserStatusItem.get_user_status_list(user)276    return status_list277def get_spot_status_list(request):278    logger.info("spot_status_list")279    logger.info("spot_id = %s" % request)280    status_list = user_model.UserStatusItem.get_spot_status_list(request)281    return status_list...installForTest.py
Source:installForTest.py  
1#!/usr/bin/python2__author__ = 'CGS'3import os, shutil, sys, distutils.core, subprocess4# Some configuration needed for this file5apps_directory = ""6apps = {"variants": "apps/variants"}7PRODUCTION = False8# TODO: better management of errors9# Some basic checks10if os.getuid() != 0:11    sys.exit("This program requires super user privileges.")12if len(sys.argv) <= 1:13    sys.exit("Please, give the name of the app you want to install. Choose among the followings: " +14        str(apps.keys()))15if sys.argv[0] != "installCGSapps.py" and "/" in sys.argv[0]:16    # If the script was not launch in the current directory, we have to make some modifications17    tmp = sys.argv[0].split("/")18    script_name = tmp.pop()19    app_directory_prefix = sys.argv[0].replace("/"+script_name,"/")20else:21    app_directory_prefix = ""22# We take the folder where hue is installed23try:24    hue_directory = subprocess.Popen("whereis hue", stdin=False, shell=True, stdout=subprocess.PIPE)25    hue_directory = str(hue_directory.communicate()[0]).split(" ")[2].strip()26except:27    hue_directory = "/usr/lib/hue"28if not os.path.exists(hue_directory) and "HUE_DIRECTORY" in os.environ:29    hue_directory = os.environ["HUE_DIRECTORY"]30if os.path.exists(hue_directory) and not os.path.exists(hue_directory+"/myapps"):31    try:32        os.makedirs(hue_directory+"/myapps")33    except:34        sys.exit("Impossible to create the folder 'myapps' in '"+hue_directory+"'.")35apps_directory = hue_directory + "/myapps"36# Some basic checks first37if not os.path.exists(hue_directory):38    sys.exit("This installation file did not find the hue directory, please create a HUE_DIRECTORY environment"39             "variable.")40# We install each application41aborted = 042for i in xrange(1, len(sys.argv)):43    app_name = sys.argv[i]44    if not app_name in apps:45        sys.exit("Invalid app name. Choose among the followings: "+str(apps.keys()))46    if not os.path.exists(app_directory_prefix+apps[app_name]):47        sys.exit("It seems the source of the app '"+app_name+"' is missing from the uncompressed zip.")48    app_directory = apps_directory+"/"+app_name49    """50    # We try to delete the eventual old folder51    if os.path.exists(app_directory):52        if PRODUCTION == True:53            reinstall = raw_input("It seems the '"+app_name+"' already exists. Do you want to reinstall it [Y/n]?")54        else:55            reinstall = "Y"56        if reinstall != "Y" and reinstall != "y":57            print("Installation of '"+app_name+"' aborted.")58            aborted += 159            continue60        else:61            try:62                shutil.rmtree(app_directory)63            except Exception as e:64                print(e.message)65                sys.exit("Impossible to delete the folder "+app_directory+". Check the access rights.")66    # We create the app67    # TODO: we do not catch correctly the errors of 'subprocess'68    try:69        print("Creating the app '"+app_name+"'...")70        app_install = subprocess.Popen("cd " + apps_directory + " && " + hue_directory +71                                       "/build/env/bin/hue create_desktop_app " + app_name,72                                       stdin=False, shell=True, stdout=subprocess.PIPE)73        app_install.communicate()74        app_install = subprocess.Popen("cd " + apps_directory + " && python " + hue_directory +75                                       "/tools/app_reg/app_reg.py --install " + app_name,76                                       stdin=False, shell=True, stdout=subprocess.PIPE)77        app_install.communicate()78    except Exception as e:79        print(e.message)80        sys.exit("Error while creating the app...")81    """82    # We copy the content of the application to the new directory83    app_src = app_directory_prefix+apps[app_name]84    try:85        print("Copying source code to app folder...")86        distutils.dir_util.copy_tree(app_src, app_directory)87    except:88        sys.exit("Impossible to copy data from '"+app_src+"' to '"+app_directory+"'.")89# We restart hue90try:91    app_install = subprocess.Popen("service hue restart", stdin=False, shell=True, stdout=subprocess.PIPE)92    app_install.communicate()93except Exception as e:94    print(e.message)95    sys.exit("Error while restarting hue.")96# The happy end97if aborted == 0:98    print("Installation successful.")99elif aborted != len(sys.argv) - 1:...run_pecific_cases.py
Source:run_pecific_cases.py  
...12    # back up old report dir å¤ä»½æ§çæµè¯æ¥åæä»¶å¤¹å°TestReport_backupä¸13    date = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))14    backup_report(date)15    suite = unittest.TestSuite()16    # suite.addTest(test_01_installapp.app_install('test_01_install'))17    suite.addTest(test_01_installapp.app_install('test_03_oversea'))18    suite.addTest(test_01_installapp.app_install('test_03_oversea_upload'))19    suite.addTest(test_01_installapp.app_install('test_04_alig_tencent'))20    suite.addTest(test_01_installapp.app_install('test_05_alig_tencent_export'))21    suite.addTest(test_01_installapp.app_install('test_06_noalig_wandoujia'))22    # suite.addTest(test_01_installapp.app_install('test_03_click_camera_btn'))23    # suite.addTest(test_01_installapp.app_install('test_04_login'))24    apks = download_channel_apks(url=ReadConfig().get_channel_url(), version=ReadConfig().get_channel_version())...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!!
