Best Python code snippet using autotest_python
3dprintremote.py
Source:3dprintremote.py  
...30# Controller functions3132@app.route('/')33def downloadprint_form(): # "Home" tab34    view_model = View("index", "STL Fetch & Slice", description="Fetch, Slice, Upload, and Print", bag={'startprint': True, 'profiles': get_profiles(), 'OCTO_ENABLED': OCTO_ENABLED})3536    return render_template('index.html', model=view_model)3738@app.route('/', methods=['POST']) # "Home" tab POST handling39def downloadprint_form_post():40    startprint = False if request.form.get('startprint') is None else True41    url = request.form['url']42    profile = request.form['profile']43    44    if not profile:45        view_model = View("index", "STL Fetch & Slice", "Fetch, Slice, Upload, and Print", '',46                        {'startprint': startprint, 'url': url, 'profile': profile, 'profiles': get_profiles(), 'OCTO_ENABLED': OCTO_ENABLED}, 'Error: Invalid form data')4748    if not is_url(url):49        view_model = View("index", "STL Fetch & Slice", "Fetch, Slice, Upload, and Print", '',50                        {'startprint': startprint, 'url': url, 'profile': profile, 'profiles': get_profiles(), 'OCTO_ENABLED': OCTO_ENABLED}, 'Error: Invalid URL')5152        return render_template('index.html', model=view_model)53        54    uri = urlparse(url)55    filename = path.basename(uri.path)5657    if not filename:58        view_model = View("index", "STL Fetch & Slice", "Fetch, Slice, Upload, and Print", '',59                        {'startprint': startprint, 'url': url, 'profile': profile, 'profiles': get_profiles(), 'OCTO_ENABLED': OCTO_ENABLED}, 'Error: Could not determine filename from the provided URL')6061        return render_template('index.html', model=view_model)6263    stl_file = download_stl(url, f'{STLPATH}\{filename}')64           65    gcode_fullpath, completed_process = send_stl_to_slicer(stl_file, profile)6667    if completed_process.returncode != 0:68        view_model = View("index", "STL Fetch & Slice", "Fetch, Slice, Upload, and Print", '',69                            {'startprint': startprint, 'url': url, 'profile': profile, 'profiles': get_profiles(), 'OCTO_ENABLED': OCTO_ENABLED}, error = f'Slicer Error: STL slicing failed. {completed_process.stdout.decode("ascii")}... {completed_process.stderr.decode("ascii")}')70                            71        return render_template('index.html', model=view_model)7273    if gcode_fullpath is None:74        view_model = View("index", "STL Fetch & Slice", "Fetch, Slice, Upload, and Print", '',75                            {'startprint': startprint, 'url': url, 'profile': profile, 'profiles': get_profiles(), 'OCTO_ENABLED': OCTO_ENABLED}, 'Slicer Error: Gcode filename detection failed. Confirm that the source is a functional STL file.')76                            77        return render_template('index.html', model=view_model)7879    if OCTO_ENABLED: # Only send sliced gcode to Octoprint when Global var is True80        try:81            octoprint_status = send_gcode_to_octoprint(gcode_fullpath, startprint)82        except Exception as e:83            view_model = View("index", "STL Fetch & Slice", "Fetch, Slice, Upload, and Print", '',84                                {'startprint': startprint, 'url': url, 'profile': profile, 'profiles': get_profiles(), 'OCTO_ENABLED': OCTO_ENABLED}, f'Octoprint Exception: {type(e)}: {e}')85        else:86            view_model = View("index", "STL Fetch & Slice", "Fetch, Slice, Upload, and Print", f'Octoprint Response: {octoprint_status}',87                                {'startprint': startprint, 'url': url, 'profile': profile, 'profiles': get_profiles(), 'OCTO_ENABLED': OCTO_ENABLED}, '')    88        89        cleanup_gcode(gcode_fullpath) # Delete the gcode file90    else:91        view_model = View("index", "STL Fetch & Slice", "Fetch, Slice, Upload, and Print", f'Sliced {filename} to: {gcode_fullpath}',92                            {'startprint': startprint, 'url': url, 'profile': profile, 'profiles': get_profiles(), 'OCTO_ENABLED': OCTO_ENABLED}, '')        93    94    return render_template('index.html', model=view_model)95    96@app.route('/profiles') # "Profiles" tab97def profiles_form():98    view_model = View("profiles", "Slicer Profiles", "Available Profiles", bag={'profiles': get_profiles(), 'OCTO_ENABLED': OCTO_ENABLED})99    return render_template('profiles.html', model=view_model)100101@app.route('/stls') # "Archived STL Printer" tab102def stls_form():103    view_model = View("stls", "Archived STL Printer", "Slice previously-downloaded STLs, Upload, and Print", bag={'stls': get_stls(), 'startprint': True, 'profiles': get_profiles(), 'OCTO_ENABLED': OCTO_ENABLED})104    return render_template('stls.html', model=view_model)105    106@app.route('/stls', methods=['POST']) # "Archived STL Printer" tab POST handling107def stlprint_form_post():108    startprint = False if request.form.get('startprint') is None else True109    stl = request.form['stl']110    profile = request.form['profile']111   112    # validate form input113    if not stl or not profile:114        view_model = View("stls", "Archived STL Printer", "Slice previously-downloaded STLs, Upload, and Print", '',115                            {'stl': stl, 'stls': get_stls(), 'profile': profile, 'profiles': get_profiles(), 'OCTO_ENABLED': OCTO_ENABLED}, "Error: Invalid form data")116        117        return render_template('stls.html', model=view_model)118119    if not path.isfile(stl):120        view_model = View("stls", "Archived STL Printer", "Slice previously-downloaded STLs, Upload, and Print", '',121                            {'stl': stl, 'stls': get_stls(), 'profile': profile, 'profiles': get_profiles(), 'OCTO_ENABLED': OCTO_ENABLED}, f'Error: {stl} not found in STL directory')122        123        return render_template('stls.html', model=view_model)124        125    stl_file = stl126127    gcode_fullpath, completed_process = send_stl_to_slicer(stl_file, profile)128129    if completed_process.returncode != 0:130        view_model = View("stls", "Archived STL Printer", "Slice previously-downloaded STLs, Upload, and Print", '',131                            {'startprint': startprint, 'stl': stl, 'stls': get_stls(), 'profile': profile, 'profiles': get_profiles(), 'OCTO_ENABLED': OCTO_ENABLED}, error = f'Slicer Error: STL slicing failed. {completed_process.stdout.decode("ascii")}... {completed_process.stderr.decode("ascii")}')132133        return render_template('stls.html', model=view_model)134135    if gcode_fullpath is None:136        view_model = View("stls", "Archived STL Printer", "Slice previously-downloaded STLs, Upload, and Print", '',137                            {'startprint': startprint, 'stl': stl, 'stls': get_stls(), 'profile': profile, 'profiles': get_profiles(), 'OCTO_ENABLED': OCTO_ENABLED}, error = 'Slicer Error: Gcode filename detection failed. Confirm that the source is a functional STL file.')138139        return render_template('stls.html', model=view_model)140141    if OCTO_ENABLED: # Only send sliced gcode to Octoprint when Global var is True142        try:143            octoprint_status = send_gcode_to_octoprint(gcode_fullpath, startprint)144        except Exception as e:145            view_model = View("stls", "Archived STL Printer", "Slice previously-downloaded STLs, Upload, and Print", '',146                                {'startprint': startprint, 'stl': stl, 'stls': get_stls(), 'profile': profile, 'profiles': get_profiles(), 'OCTO_ENABLED': OCTO_ENABLED}, f'Octoprint Exception: {type(e)}: {e}')147        else:148            view_model = View("stls", "Archived STL Printer", "Slice previously-downloaded STLs, Upload, and Print",149                                f'Octoprint Response: {octoprint_status}', {'startprint': startprint, 'stl': stl, 'stls': get_stls(), 'profile': profile, 'profiles': get_profiles(), 'OCTO_ENABLED': OCTO_ENABLED}, '')150        151        cleanup_gcode(gcode_fullpath) # Delete the gcode file152    else:153        view_model = View("stls", "Archived STL Printer", "Slice previously-downloaded STLs, Upload, and Print",154                            f'Sliced {stl} to: {gcode_fullpath}', {'startprint': startprint, 'stl': stl, 'stls': get_stls(), 'profile': profile, 'profiles': get_profiles(), 'OCTO_ENABLED': OCTO_ENABLED}, '')155156    return render_template('stls.html', model=view_model)157    158# Helper functions159160def download_stl(url, filename):161# Download the STL file to the STL directory162    r = requests.get(url)163    with open(filename, 'wb') as f:164        f.write(r.content)165166    return f.name167168def send_stl_to_slicer(stl_file, profile):169# Slice the STL and extract the resultant path from the slicer output170    command = f'"{PRUSASLICERPATH}\prusa-slicer-console.exe" --gcode --load "{CURRENTPATH}\{profile}" "{CURRENTPATH}\{stl_file}"'171    completed_process = subprocess.run(command, shell=True, capture_output=True)172    gcode_fullpath = get_gcode_fullpath_from_prusa_slicer_output(completed_process.stdout.decode("utf-8"))173174    return gcode_fullpath, completed_process175176def get_gcode_fullpath_from_prusa_slicer_output(slicer_output):177# Extract the gcode path from the slicer output178    pattern = r"[a-zA-Z]:\\([a-zA-Z0-9() ]*\\)*\w*.*\w*.gcode" #full path179    match = re.search(pattern, slicer_output)180    if match is None:181        return182    return match.group()183184def send_gcode_to_octoprint(gcode_fullpath, startprint):185# Using the OctoRest-generated Octoprint client, upload the gcode to Octoprint server186# 'startprint' bool is determined by the "Start printing after upload" switch in UI187    with open(gcode_fullpath, 'rb') as f:188        gcode_tuple = (path.basename(gcode_fullpath), f)189        try:190            client = make_octoprint_client(OCTO_HOST, OCTO_APIKEY)191        except Exception as e:192            raise e193        upload_process = client.upload(gcode_tuple, print=startprint)194        # NOTE: If you are NOT using the OctoRest branch specified in requirements.txt, print=True will fail here..195        # ..as a workaround, uncomment the 'client.select..' line below. This won't be necessary after OctoRest Release >0.4.196        #client.select(path.basename(gcode_fullpath), print=startprint)197    return upload_process198    199def make_octoprint_client(octoprintHost, octoprintApiKey):200# Create an Octoprint client using OctoRest module201    try:202        client = OctoRest(url=octoprintHost, apikey=octoprintApiKey)203        return client204    except Exception as e:205        raise e206207def is_url(url):208  try:209    result = urlparse(url)210    return all([result.scheme, result.netloc])211  except ValueError:212    return False213    214def cleanup_gcode(filename):215# Delete gcode file that was generated by send_stl_to_slicer()216    remove(filename)217    218def get_stls():219# Get list of STLs for display/selection on "Archived STL Printer" tab220    return glob.glob(f'{STLPATH}/*.stl', recursive=False)221222def get_profiles():223# Get list of profiles for display/selection within each tab224    return glob.glob(f'{ROOTPROFILESPATH}/*.ini', recursive=False)225
...reconnectwifi.py
Source:reconnectwifi.py  
...65            text += byte   66    #print("TEXT:", text.split('\r\n'))67    return text6869def get_profiles():70    profiles = list()71    log_info("Wi-Fi Getting Wireless Profiles ...")72    text = cmd("netsh", "wlan", "show", "profiles")73    if "All User Profile" in text:74        for line in text.split('\r\n'):75            if "All User Profile" in line:76                idx = line.find(":")77                if idx > -1:78                    ssid = line[idx + 1:].strip()79                    if ssid: profiles.append(ssid)80    log_info(f"Available Wireless Profiles are {profiles}")81    return profiles8283def connect_profile(profile):84    log_info(f"Wi-Fi Connecting to {profile} ...")85    text = cmd("netsh", "wlan", "connect", f"name={profile}", f"ssid={profile}")86    time.sleep(5)87    checked = "request was completed successfully" in text or profile == get_connected_profile()88    return checked8990def get_connected_profile():91    wifi = ""92    log_info("Wi-Fi Getting Connected Profile ...")93    text = cmd("netsh", "wlan", "show", "interfaces", "|", "findstr", "SSID")94    if "SSID" in text:95        for line in text.split('\r\n'):96            words = [ word.strip() for word in line.split(':') if word ]97            if "SSID" in words:98                wifi = words[-1]99                break100    log_info(f"Wi-Fi Connected Network Found is '{wifi}'.")101    return wifi102103def get_interface_info():104    info = dict()105    log_info("Wi-Fi Getting Interface Information ...")106    text = cmd("netsh", "wlan", "show", "interfaces")107    text = [line.strip() for line in text.split('\r\n') if line]108    indexes = [idx for idx, line in enumerate(text) if line.startswith("Name")]109    end = len(text)110    stop = len(indexes)111    for pos, idx in enumerate(indexes):112        if pos + 1 < stop: 113            items = list((tuple(line.split(':', 1)) for line in text[idx:indexes[pos + 1]]))114        else:115            items = list((tuple(line.split(':', 1)) for line in text[idx:]))116        temp = dict((key.strip(), val.strip()) for key, val, *extra in items)117        info.update({temp.get('Profile'): temp})118    log_info("Wi-Fi Connected Interface info", info)119    return info120121def delete_profile(profile):122    log_info(f"Wi-Fi Deleting profile: {profile}")123    text = cmd("netsh", "wlan", "delete", "profile", f"name={profile}").strip()124    checked = "is deleted from interface" in text or profile not in get_profiles()125    return checked126127def add_profile(profile):128    if not os.path.isfile(profile):129        files = get_files()130        if files:131            profile = files.get(profile) # Getting profile's file 132    log_info(f"Wi-Fi Adding profile: {profile}")133    text = cmd("netsh", "wlan", "add", "profile", f"filename={profile}", "user=all")134    checked = "is added on interface" in text or profile in get_profiles()135    return checked136   137def backup_profiles():138    text = cmd("netsh", "wlan", "export", "profile", "key=clear", f"folder={PROFILEDIR}")139    if "successfully" not in text:140        return False141    else:142        saved = [line for line in text.split('\r\n') if line]143        found = get_profiles()144        ret = len(saved) == len(found)145        return ret146    147def delete_profiles():148    if backup_profiles():149        profiles = get_profiles()150        log_info("Deleting All Wi-Fi profiles", profiles)151        for profile in profiles:152            delete_profile(profile)153    return len(get_profiles()) == 0154155def restore_profiles():156    files = get_files()157    found = get_profiles()158    log_info("Restoring Profiles", files)159    for profile in files:160        if profile not in found: 161            add_profile(profile)162    found = get_profiles()163    checked = [profile in found for profile in files]164    if all(checked):165        log_info("Wi-Fi Profiles Restored", files, found)166    else:167        log_info("Wi-Fi Unabled to restore profiles")168    return all(checked)169170def get_networks():171    networks = list()172    text = cmd("netsh", "wlan", "show", "networks", "|", "findstr", "SSID")173    if "SSID" in text:174        for line in text.split('\r\n'):175            idx = line.find(":")176            if idx > -1:177                ssid = line[idx + 1:].strip()178                if ssid: networks.append(ssid)179    log_info("Available Wi-Fi Networks", networks)180    return networks181182def connect_suitable_profile():183    log_info("Wi-Fi Connecting Suitable Network ...")184    suitable = ""185    profiles = get_profiles()186    networks = get_networks()187    possibles = [wifi for wifi in profiles if wifi in networks]188    if possibles:189        print("Suitable Profiles", possibles)190        if len(possibles) == 1:191            suitable = possibles[-1]192        else:193            suitables = dict()194            for profile in possibles:195                if connect_profile(profile):196                    suitables.update(get_interface_info())197            print("\nPROFILES:\n", suitables)198            strong = filter_profiles(suitables, "good")199            if strong:200                for profile, info in strong.items():201                    if info.get().lower() == 'open':202                        suitable = profile203            if suitable == "":204                secured = filter_profiles(suitables)205                strong = filter_profiles(secured)206                if strong:207                    for profile, info in strong.items():208                        suitable = profile209                elif secured:210                    for profile, info in secured.items():211                        suitable = profile212                        break213        log_info(f"\tWi-Fi Suitable Profile is {suitable}")214    else:215        log_info("\tPlease Connect to a Network")216        input("Press Enter to Continue ...")217    return suitable218219def get_target_profile():220    thiswifi = get_connected_profile() or connect_suitable_profile()221    profiles = get_profiles() + get_networks()222    checked = thiswifi not in profiles223    while checked:224        time.sleep(5)225        profiles = get_profiles() + get_networks()226        if thiswifi == "":227            thiswifi = get_connected_profile() or connect_suitable_profile()228        checked = thiswifi not in profiles229    log_info(f"Target Wifi is {thiswifi}")   230    return thiswifi231    232def loop_auto_reconnect():233    target = get_target_profile()234    log_info(f"Wi-Fi Target Profile is {target}")235    if backup_profiles():236        log_info("Wi-Fi Profiles Backed up", get_files())237        try: 238            while True:239                connected = get_connected_profile()
...test_profiles.py
Source:test_profiles.py  
...30        })31        with exi, platform, listdir, env:32            self.assertEqual([33                join(basename(dirname(item)), basename(item))34                for item in get_profiles('firefox')35            ], expected_files)36        # without APPDATA37        env = patch('frostmark.profiles.environ', {})38        with exi, platform, listdir, env:39            self.assertEqual([40                join(basename(dirname(item)), basename(item))41                for item in get_profiles('firefox')42            ], expected_files)43    def test_profile_firefox_macos(self):44        '''45        Test fetching Firefox profiles on macOS.46        '''47        from frostmark.profiles import get_profiles48        found_profiles = ['profile1.default', 'profile2.default']49        expected_files = [50            join('profile1.default', 'places.sqlite'),51            join('profile2.default', 'places.sqlite')52        ]53        exi = patch('frostmark.profiles.exists')54        platform = patch('sys.platform', 'darwin')55        listdir = patch(56            'frostmark.profiles.listdir',57            return_value=found_profiles58        )59        with exi, platform, listdir:60            self.assertEqual([61                join(basename(dirname(item)), basename(item))62                for item in get_profiles('firefox')63            ], expected_files)64    def test_profile_firefox_linux(self):65        '''66        Test fetching Firefox profiles on GNU/Linux distros.67        '''68        from frostmark.profiles import get_profiles69        found_profiles = ['profile1.default', 'profile2.default']70        expected_files = [71            join('profile1.default', 'places.sqlite'),72            join('profile2.default', 'places.sqlite')73        ]74        exi = patch('frostmark.profiles.exists')75        platform = patch('sys.platform', 'linux')76        listdir = patch(77            'frostmark.profiles.listdir',78            return_value=found_profiles79        )80        with exi, platform, listdir:81            self.assertEqual([82                join(basename(dirname(item)), basename(item))83                for item in get_profiles('firefox')84            ], expected_files)85    def test_profile_opera_win(self):86        '''87        Test fetching Opera profiles on Windows.88        '''89        from frostmark.profiles import get_profiles90        found_profiles = ['Opera stable']91        expected_files = [92            join('Opera stable', 'Bookmarks')93        ]94        exi = patch('frostmark.profiles.exists')95        platform = patch('sys.platform', 'win32')96        listdir = patch(97            'frostmark.profiles.listdir',98            return_value=found_profiles99        )100        # with APPDATA101        env = patch('frostmark.profiles.environ', {102            'APPDATA': 'dummy'103        })104        with exi, platform, listdir, env:105            self.assertEqual([106                join(basename(dirname(item)), basename(item))107                for item in get_profiles('opera')108            ], expected_files)109        # without APPDATA110        env = patch('frostmark.profiles.environ', {})111        with exi, platform, listdir, env:112            self.assertEqual([113                join(basename(dirname(item)), basename(item))114                for item in get_profiles('opera')115            ], expected_files)116    def test_profile_unsupported_browser(self):117        '''118        Test fetching profiles for an unsupported browser.119        '''120        from frostmark.profiles import get_profiles121        self.assertEqual(get_profiles('not_supported'), [])122    def test_profile_all_browsers(self):123        '''124        Test fetching all profiles.125        '''126        from frostmark.profiles import get_all_profiles, SUPPORTED_BROWSERS127        with patch('frostmark.profiles.get_profiles') as gprof:128            get_all_profiles()129            self.assertEqual(130                gprof.call_args_list,131                [call(b) for b in SUPPORTED_BROWSERS]132            )133    @staticmethod134    def test_profile_print():135        '''...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!!
